带有额外过滤器的 Foreach 循环 - >需要识别最后一个条目



我正在尝试在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> }

任何人都可以阐明如何在这种情况下获得最后一个条目吗?谢谢

你应该写一个函数来过滤数组,然后你可以像这样弹出最后一项:

// 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
<?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>"
?>

最新更新