PHP排序多维数组

时间:2014-02-26 14:18:12

标签: php arrays sorting

我想以特定的方式对多维数组进行排序。

我有一个这样的数组:

Array (
 [551691] => Array (
   [19129287] => Array (
     [value] => cccccc
     [id] => 19129287
     [col] => 1
   )
   [19129288] => Array (
     [value] => bbbbb
     [id] => 19129288
     [col] => 2
   )
 )

 [550141] => Array (
   [19071703] => Array (
     [value] => aaaaa
     [id] => 19071703
     [col] => 1
   )
   [19071706] => Array (
     [value] => ccccc
     [id] => 19071706
     [col] => 2
   )
 )

 [550139] => Array (
   [19071675] => Array (
     [value] => bbbbb
     [id] => 19071675
     [col] => 1
   )
   [19071676] => Array (
     [value] => ddddd
     [id] => 19071676
     [col] => 2
   )
)
)

我想按[value]为特定的[col]

排序这个数组

例如[col]的值为1:

带有键550141的第一级数组应移动到第一个位置,因为数组中的值为[col] => 1是“aaaaa”

Array (

 [550141] => Array ( // <= Moved at first position "value" for col 1 is aaaa
   [19071703] => Array (
     [value] => aaaaa
     [id] => 19071703
     [col] => 1
   )
   [19071706] => Array (
     [value] => ccccc
     [id] => 19071706
     [col] => 2
   )
 )

 [550139] => Array ( // <= Moved at second position
   [19071675] => Array (
     [value] => bbbbb
     [id] => 19071675
     [col] => 1
   )
   [19071676] => Array (
     [value] => ddddd
     [id] => 19071676
     [col] => 2
   )
)

 [551691] => Array (
   [19129287] => Array (
     [value] => cccccc
     [id] => 19129287
     [col] => 1
   )
   [19129288] => Array (
     [value] => bbbbb
     [id] => 19129288
     [col] => 2
   )
 )
)

如果有人有个好主意......: - )

由于

2 个答案:

答案 0 :(得分:0)

您可以使用http://php.net/usort

编写自己的排序功能

你可能需要像

这样的东西
usort($array, function($a,$b) {
  return ($a['value']<$b['value'])?1:-1;
});

显然你需要调整它以适应你的情况,并可能把它放到{}循环中,因为你实际上正在对子数组进行排序。

答案 1 :(得分:0)

最终我找到了解决方案。我不知道是否是最好的方式,但它有效:

$sortarray = array();

foreach ($datas as $datas_key => $s) {
    foreach ($s as $itemId => $item) {
        if ($item['col'] == 2) {
            $sortarray[] = array(
                'sid' => $datas_key,
                'value' => $item['value']
            );
        }
    }
}

usort($sortarray, function($a,$b) {
    return ($a['value']<$b['value'])?-1:1;
});

$datas_sorted = array();
foreach ($sortarray as $new_sort) {
    $datas_sorted[$new_sort['sid']] = $datas[$new_sort['sid']];
}