PHP
//Test Data
$ ar = array (
Array (id => 1, pid => 0),
Array (id => 2, pid => 0),
Array (ID => 3, PID => 2),
Array (id => 4, pid => 0),
Array (id => 5, pid => 3),
Array (id => 6, pid => 1),
Array (id => 7, pid => 1),
Array (id => 8, pid => 6),
Array (id => 9, pid => 7),
Array (ID => 10, PID => 9)
);
// Sort function
Function CMD ($ A, $ B) {
IF ($ A [PID] == $ B [PID]) Return 0;
RETURN $ A [PID]> $ B [PID]? 1: -1;
}
// Sort, in order to avoid the data of the parent node in the sub-node, this situation often occurs when the data is modified multiple times.
// The purpose of sorting is to prevent the chaos caused by this situation.
UASORT ($ AR, CMD);
/ / Define an object array
$ d = array ();
// Define the index number, used to record the position of the node in the target array
$ 有D = array ();
Foreach ($ AS $ V) {
$ v [child] = array (); // Add a Child item to each node
IF ($ V [PID] == 0) {
$ i = count ($ d);
$ D [$ I] = $ V;
$ IND [$ v [id]] = & $ d [$ i];
} else {
$ i = count ($ IND [$ V [PID]] [Child]);
$ IND [$ V [PID]] [Child] [$ I] = $ V;
$ IND [$ V [ID]] = & $ IND [$ V [PID]] [Child] [$ I];
}
}
//test result
Echo "
";Print_r ($ d);
ECHO " pre>";
?>