duanmao2774 2012-05-27 22:01
浏览 193
已采纳

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 "
";
        $j++;
    }
?>  
  • 写回答

8条回答 默认 最新

  • dongyongkui6329 2012-05-27 22:04
    关注

    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]);
    }
    

    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.

    Reversing the Array

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题