The two-dimensional array sorting problem of ph. for help, the two-dimensional array with detailed requirements for initial status is like this.
$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'),)
Sort by name by default, but change now
It is still sorted by the name field, but also by the parentNum field. parentNum indicates its parent category, so the final result should be
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'),
How can I implement it using code? I tried for a long time. why not?
Reply to discussion (solution)
$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 ))
This situation is a bit idealistic, but it is not true. thank you.
That's it, but I cannot be born out of nothing.
In fact, this problem cannot be solved by sorting.
There are many posts in the essence area. you should take a closer look.
If sorting can solve the problem of querying the adjacent list, do so many people need to study it?
That's it, but I cannot be born out of nothing.
In fact, this problem cannot be solved by sorting.
There are many posts in the essence area. you should take a closer look.
If sorting can solve the problem of querying the adjacent list, do so many people need to study it?
I have researched it and need to use recursion. thank you.