具有额外过滤器的Foreach循环 - >需要确定最后一个条目

时间:2013-01-29 00:20:17

标签: php 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> }

有人能说明如何在这种情况下获得最后一个条目吗?感谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>"

?>
相关问题