ph two-dimensional array sorting puzzles, requesting help with detailed requirements
The initial state of the two-dimensional array is 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 '),
)
The default is sorted by the Name field, but now you need to change
Still sort by the name field, but also to sort by the Parentnum field, Parentnum is the parent category for it, so the end 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 to use code to achieve it? I've been trying for quite a while.
------to solve the idea----------------------
$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
)
)