1

foreachループの最後のエントリを取得しようとしていますが、これまでのところ苦労しています。私の最大の問題は、foreachループ内に入ると、投稿が0のすべての作成者を削除して配列をフィルター処理する必要があることです。これはこれまでの私のコードです:

$authors = get_users('orderby=nicename');


foreach ($authors as $author ) {
      if ( count_user_posts( $author->id ) >= 1 ) { IF LAST {special <li>} else {normal <li> }

誰かがこのシナリオの最後のエントリを取得する方法に光を当てることができますか?ありがとう

4

2 に答える 2

2

配列をフィルタリングする関数を作成する必要があります。そうすれば、次のように最後の項目をポップできます。

// use this section of code in PHP >= 5.3 - utilizes anonymous function
$filtered_array = array_filter($authors, function($author) {
    if(count_user_posts($author->id) >= 1) return true;
    return false;
});

// use this section of code for older versions of PHP - uses regular function
function author_filter($author) {
    if(count_user_posts($author->id) >= 1) return true;
    return false;
}
$filtered_array = array_filter($authors, 'author_filter');

// the rest is the same regardless of PHP version
$last_author = array_pop($filtered_array);

// output
foreach($filtered_array as $author) {
    // regular output
}
// then do special output for $last_author
于 2013-01-29T00:26:31.630 に答える
0
<?php
$numItems = count($arr);
echo "<ul>";
for($i = 0; $i < $numItems; $i++) {
    if(as_zero_post){
        //$i++;
        continue;       
    }
    $i == $numItems-1 ? "<li class='last-item'>".$arr[$i]."</li>" : "<li class='normal-item'>".$arr[$i]."</li>";

} 
echo "</ul>"

?>
于 2013-01-29T01:07:31.423 に答える