douganggu4392 2015-03-09 23:40
浏览 57
已采纳

按字母顺序循环浏览php数组

I have a PHP Loop that loops through data, i want to be able to echo all of this data alphabetically.

i currently use an array:

$output[]=array();
foreach($WHM_Servers as $whm) {
    foreach($server->list_accounts() as $ret) {
            $output[]= '<tr class="notfirst">
            <td>'.$ret["domain"].'</td>
            <td>'.$ret["user"].'</td>
            <td>'.CompanyInfoLookup($result["customer"], 'company').'</td>
            <td>'.$ret["startdate"].'</td>
            <td>'.$ret["starttime"].'</td>
            <td>'.$ret["disklimit"].'</td>
            <td>'.$ret["diskused"].'</td>
            </tr>';
    }
}

would i be able to add a key in the array and then echo the array alphabetically from the keys

  • 写回答

1条回答 默认 最新

  • duanpo7796 2015-03-09 23:58
    关注

    A few different ways to do this, I chose to write a user defined sort function.

    $accounts = array();
    $accounts[]['name'] = "Tom";
    $accounts[]['name'] = "Frank";
    $accounts[]['name'] = "Zed";
    $accounts[]['name'] = "Aaron";
    
    function compareNames($a, $b){
        return strcmp($a['name'], $b['name']);
    }
    
    usort($accounts, "compareNames");
    
    var_dump($accounts);
    

    Output:

    array(4) {
      [0]=>
      array(1) {
        ["name"]=>
        string(5) "Aaron"
      }
      [1]=>
      array(1) {
        ["name"]=>
        string(5) "Frank"
      }
      [2]=>
      array(1) {
        ["name"]=>
        string(3) "Tom"
      }
      [3]=>
      array(1) {
        ["name"]=>
        string(3) "Zed"
      }
    }
    

    This is a standalone example. To apply it to your example, you need to store the data: $accounts = $server->list_accounts(), sort it: usort($accounts, "compareNames");, and then pass it in to your loop: foreach($accounts as $ret) {

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程