douju2053 2013-05-23 17:21
浏览 58
已采纳

在PHP中,如何基于键[关闭]排序关联数组排序

I've a nested associative array like the one below and need help sorting the array for each of the keys such as 'first_name' and 'score'.

For example:

Array
(
    [12345] => Array
        (
            [75] => Array
                (
                    [first_name] => Xen
                    [score] => 245
                )
        )

    [9876] => Array
        (
            [75] => Array
                (
                    [first_name] => Shane
                    [score] => 300
                )
        ) 
    [4567] => Array
        (
            [75] => Array
                (
                    [first_name] => Dan
                    [score] => 100
                )
        ) 
)

The result should have the array sorted by the keys in ascending order:

Array
(
    [first_name] => Array
                 (
                   [0] => 4567
                   [1] => 9876
                   [2] => 12345
                 )

    [score] => Array
           (
             [0] => 4567
             [1] => 12345
             [2] => 9876
           )
)
  • 写回答

1条回答 默认 最新

  • dreamy6301 2013-05-23 17:25
    关注

    ksort is PHP's function to sort by key. So to sort an array $arr by its keys, do:

    ksort($arr);
    

    Note that ksort returns a boolean (success or failure), so you shouldn't do $arr = ksort($arr);. ksort modifies the original array.

    To sort a multidimensional associative array (say, an associative array of associative arrays) recursively by keys, try the user-provided function at the bottom of the ksort manual page (I haven't tried this, but it looks like it will work just fine):

    function deep_ksort(&$arr) {
        ksort($arr);
        foreach ($arr as &$a) {
            if (is_array($a) && !empty($a)) {
                deep_ksort($a);
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办