【问题标题】:PHP order by value in multidimensional array [duplicate]PHP按多维数组中的值排序[重复]
【发布时间】:2019-12-28 23:45:09
【问题描述】:

我有一个格式如下的数组:

Array
(
    [123451000] => Array
        (
            [total] => 70
            [total_tech] => 36
            [duration] => 300
        )

    [123451001] => Array
        (
            [total] => 9
            [total_tech] => 3
            [duration] => 197
        )

    [123451002] => Array
        (
            [total] => 103
            [total_tech] => 97
            [duration] => 273
        )
)

我正在浏览它,但想知道是否可以通过total 订购?

编辑:我当前的 foreach 循环

foreach($agents as $agent => $option) {
    //$talktime = secondsToTime($x["talktime_sum"]);
    $display.= '<tr>
    <td>'.get_dtypes('phone', $agent).'</td>
    <td>'.number_format($option["total_calls"]).'</td>
    <td>'.number_format($option["technical_calls"]).'</td>
    <td>'.number_format($option["sales_calls"]).'</td>
    <td>'.number_format($option["other_calls"]).'</td>
    <td>'.$option["total_duration"].'</td>
    </tr>';
}

【问题讨论】:

    标签: php


    【解决方案1】:
    uasort($array, function ($a, $b) {
        return $a['total'] <=> $b['total'];
    });
    

    usort 是一个通过快速排序对数组进行排序的函数,使用用户给定的函数进行比较。

    ~~uksort 是它的一个变种,它保留了数组的键~~

    &lt;=&gt; 是“宇宙飞船”运算符,如果左侧较大则返回 -1,如果右侧较大则返回 1,如果相等则返回 0

    编辑 uksort 使用密钥进行排序,而不是保留密钥。 uasort 是按值排序并保留数组键的那个

    【讨论】:

    • 查看我的更新 - 我是否用你的代码替换我当前的 foreach 循环 - 使用 uasort 函数?
    • 您使用循环打印它,在打印之前使用排序对数组进行排序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    相关资源
    最近更新 更多