如何将 PHP 对象定义为数组中的最后一项


How to define a PHP object as the last item in an array?

在下面的代码中,我想将对象"$activeclass"作为DIV类应用。 我以为我包含的结束指针只会将其应用于数组的最后一次迭代,而是将类应用于所有迭代。

<div id="right_bottom">
                <?
                $content = is_array($pagedata->content) ? $pagedata->content : array($pagedata->content);
                foreach($content as $item){
                $activeclass = end($content) ? 'active' : ' ';
                    ?>
                    <div id="right_side">
                           <div id="<?=$item->id?>" class="side_items <?=$activeclass?>">
                             <a class="content" href="<?=$item->id?>"><img src="<?=PROTOCOL?>//<?=DOMAIN?>/img/content/<?=$item->image?>"><br />
                             <strong><?=$item->title?></strong></a><br />
                             <h2><?=date('F j, Y',  strtotime($item->published))?></h2><br />
                         </div>
                    </div>
                    <?
                }
                ?>
</div>

有什么想法我犯错了吗? 如何将类$activeclass仅应用于"foreach"语句的最后一次迭代?

最简单的方法是保持计数:

$i = 0; $size = count( $content);
foreach( $content as $item) {
    $i++;
    $activeclass = ( $i < $size) ? '' : 'active';
}

或者,您可以将最后一个元素与当前元素进行比较(如果您的数组是从 0 开始连续的数字索引 [感谢 webbiedave 指出此方法所做的假设]):

$last = count( $content) - 1;
foreach( $content as $item) {
    $activeclass = ( $content[$last] === $item) ? 'active' : '';
}

请注意,如果您的数组具有重复项,则此方法将不起作用。

最后,您可以通过以下方式比较索引:

// Numerical or associative
$keys = array_keys($content); 
$key = array_pop($keys); // Assigned to variables thanks to webbiedave
// Consecutive numerically indexed
$key = count( $content) - 1; 
foreach( $content as $current_key => $item) {
    $activeclass = ( $current_key === $key) ? 'active' : '';
}
$activeclass = end($content) ? 'active' : ' ';

end() 函数返回数组中的最后一个元素,因此您基本上是在检查数组是否有最后一个元素(除非它是空的,否则它总是会)。

这是对你做错了什么的解释 - nick 有关于如何使用计数器修复它的答案。

从以下链接尝试此方法 http://blog.actsmedia.com/2009/09/php-foreach-last-item-last-loop/

$last_item = end($array);
$last_item = each($array);
reset($array);
foreach($array as $key => $value)
{
    // code executed during standard iteration
    if($value == $last_item['value'] && $key == $last_item['key'])
    {
    // code executed on the 
            // last iteration of the foreach loop
    }
 }