对多维数组进行排序,同时保持其在PHP中的排列

时间:2017-11-02 01:10:47

标签: php arrays sorting multidimensional-array

我正在尝试对此数组进行排序,但与此同时,我正在尝试更改索引和所有元素。

我想按[name]对数组进行排序。所以带有Array ( [0] => stdClass Object ( [tid] => 992 [vid] => 70 [name] => Global People [description] => [format] => filtered_html [weight] => 0 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [1] => stdClass Object ( [tid] => 1206 [vid] => 70 [name] => Global Department Head [description] => [format] => filtered_html [weight] => 1 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [2] => stdClass Object ( [tid] => 986 [vid] => 70 [name] => Global Private Leaders [description] => [format] => filtered_html [weight] => 2 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [3] => stdClass Object ( [tid] => 1208 [vid] => 70 [name] => Service Line Partnership [description] => [format] => filtered_html [weight] => 3 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [4] => stdClass Object ( [tid] => 984 [vid] => 70 [name] => Digital Stakeholders [description] => [format] => filtered_html [weight] => 4 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [5] => stdClass Object ( [tid] => 990 [vid] => 70 [name] => Regional Team [description] => [format] => filtered_html [weight] => 5 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [6] => stdClass Object ( [tid] => 988 [vid] => 70 [name] => Digital Team [description] => [format] => filtered_html [weight] => 6 [depth] => 0 [parents] => Array ( [0] => 0 ) ) [7] => stdClass Object ( [tid] => 1210 [vid] => 70 [name] => Cross Cutting Functions [description] => [format] => filtered_html [weight] => 7 [depth] => 0 [parents] => Array ( [0] => 0 ) ) ) 的数组[7]将是第一个节点,依此类推......

这是数组:

 foreach ($terms as $key => $row) {
      $temp_array[$key] = $row['name'];
 }

array_multisort($temp_array, SORT_ASC, $data);

这是我试过的:

(但它不起作用)

const result = array1.map(a1 => ({...a1, values: 
  array2.reduce((r, a2) => a2.name === a1.name ? [...r, a2.value] : r, [])
}));

感谢。

1 个答案:

答案 0 :(得分:1)

您应该可以使用PHP usort来解决此问题:

http://php.net/manual/en/function.usort.php

// Example with your $terms
function cmp($a, $b)
{
    return strcmp($a->name, $b->name);
}

usort($terms, "cmp");