Reverse order of foreach list items

后端 未结 8 1497
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 16:31

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.



        
相关标签:
8条回答
  • 2020-12-02 17:07

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 17:09

    If your array is populated through an SQL Query consider reversing the result in MySQL, ie :

    SELECT * FROM model_input order by creation_date desc
    
    0 讨论(0)
提交回复
热议问题