foreach列表项的倒序 [英] Reverse order of foreach list items

查看:559
本文介绍了foreach列表项的倒序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想颠倒此代码的列表项的顺序.基本上,这是从最旧的到最近的几年时间,而我正在尝试反转该输出.

I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.

<?php
    $j=1;     
    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?>  

推荐答案

向后走动

如果您正在寻找纯PHP解决方案,则还可以简单地从列表中倒数,从前到后访问它:

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

上面的方法将$index设置为元素总数,然后开始从头到尾访问它们,从而减少了下一次迭代的索引值.

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

您还可以利用 array_reverse函数反转数组的值,从而可以以相反的顺序访问它们:

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

这篇关于foreach列表项的倒序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆