当前位置:Gxlcms > PHP教程 > ph二维数组排序难题,内附详细需求

ph二维数组排序难题,内附详细需求

时间:2021-07-01 10:21:17 帮助过:5人阅读

ph二维数组排序难题,请求帮助,内附详细需求
初始状态的二维数组是这样的
$a = array(
array('name'=>'a','num'=>'1','parentNum'=>'0'),
array('name'=>'b','num'=>'2','parentNum'=>'0'),
array('name'=>'c','num'=>'3','parentNum'=>'0'),
array('name'=>'d','num'=>'4','parentNum'=>'1'),
array('name'=>'e','num'=>'5','parentNum'=>'2'),
array('name'=>'f','num'=>'6','parentNum'=>'0'),
array('name'=>'g','num'=>'7','parentNum'=>'0'),
)

默认按照name字段排序,但是现在需要改变
仍然按照name字段排序,但是同时也要按照parentNum字段排序,parentNum是代表它的父级分类,所以最终的结果应该是
  array('name'=>'a','num'=>'1','parentNum'=>'0'),
array('name'=>'d','num'=>'4','parentNum'=>'1'),
array('name'=>'b','num'=>'2','parentNum'=>'0'),
array('name'=>'e','num'=>'5','parentNum'=>'2'),
array('name'=>'c','num'=>'3','parentNum'=>'0'),
array('name'=>'f','num'=>'6','parentNum'=>'0'),
array('name'=>'g','num'=>'7','parentNum'=>'0'),

请问怎么用代码实现呢?我试了蛮久不怎么会?
------解决思路----------------------
$a = array(
array('name'=>'a','num'=>'1','parentNum'=>'0'),
array('name'=>'b','num'=>'2','parentNum'=>'0'),
array('name'=>'c','num'=>'3','parentNum'=>'0'),
array('name'=>'d','num'=>'4','parentNum'=>'1'),
array('name'=>'e','num'=>'5','parentNum'=>'2'),
array('name'=>'f','num'=>'6','parentNum'=>'0'),
array('name'=>'g','num'=>'7','parentNum'=>'0'),
);

foreach($a as $r) {
$p[] = $r['parentNum'] ? $r['parentNum'] : $r['num'];
}
array_multisort($p, $a);
print_r($a);
Array
(
[0] => Array
(
[name] => a
[num] => 1
[parentNum] => 0
)

[1] => Array
(
[name] => d
[num] => 4
[parentNum] => 1
)

[2] => Array
(
[name] => b
[num] => 2
[parentNum] => 0
)

[3] => Array
(
[name] => e
[num] => 5
[parentNum] => 2
)

[4] => Array
(
[name] => c
[num] => 3
[parentNum] => 0
)

[5] => Array
(
[name] => f
[num] => 6
[parentNum] => 0
)

[6] => Array
(
[name] => g
[num] => 7
[parentNum] => 0
)

)

人气教程排行