如何使用array_multisort()对这种多维数组进行排序?

时间:2021-10-21 15:58:06

Let’s say we have an array like that

假设有这样一个数组。

array(2) {
  [2012]=>
  array(2) {
    [0]=>
    array(2) {
      ["file"]=>
      string(3) "aaa"
      ["mtime"]=>
      int(1347534106)
    }
    [1]=>
    array(2) {
      ["file"]=>
      string(3) "bbb"
      ["mtime"]=>
      int(1346293592)
    }
  }
  [2011]=>
  array(2) {
    [0]=>
    array(2) {
      ["file"]=>
      string(3) "ccc"
      ["mtime"]=>
      int(1316753224)
    }
    [1]=>
    array(2) {
      ["file"]=>
      string(3) "ddd"
      ["mtime"]=>
      int(1318671936)
    }
  }
}

I want this array to be sorted descending by first index (2012,2011[,2010,…]) and every subarray (every value of the root array) sorted descending by mtime values, but I cannot get how to apply array_multisort() to this. I could pass first key as '2012' and then it would be passed as a key of an associative array, but how to sort by mtime then?

我希望这个数组按第一个索引(2012,2011[,2010,…])和每个子数组(根数组的每个值)按mtime值排序,但我无法得到如何将array_multisort()应用于此。我可以将第一个键作为“2012”传递,然后它会被作为一个关联数组的键传递,但是如何排序呢?

1 个解决方案

#1


0  

Given your toplevel array is $array, you can do like this:

如果你的toplevel数组是$array,你可以这样做:

krsort($array);
foreach ($array as &$arr) {
    uasort($arr, 'cmp');
}

function cmp($a, $b) {
    return $b['mtime'] - $a['mtime'];
}

var_dump($array); //to check results

that should do what you want.

那应该做你想做的。

Update: changed ksort for krsort for obtaining the descendin years as OP wanted.

更新:为krsort更改了ksort以获得OP所需的后代。

#1


0  

Given your toplevel array is $array, you can do like this:

如果你的toplevel数组是$array,你可以这样做:

krsort($array);
foreach ($array as &$arr) {
    uasort($arr, 'cmp');
}

function cmp($a, $b) {
    return $b['mtime'] - $a['mtime'];
}

var_dump($array); //to check results

that should do what you want.

那应该做你想做的。

Update: changed ksort for krsort for obtaining the descendin years as OP wanted.

更新:为krsort更改了ksort以获得OP所需的后代。