All right...... The name of the problem is a bit of a rip ...
There are array inputs as follows:
[{id=> ' xx '},{id=> '},{id=> '},{id= ' 0001 '},{id=> ' 2234 '}]
Now you want to organize this array into the following form:
[{id=> ' xx ',children=>{{id=> ' 0001 '}},{id=> ' ", children=>{}},{id=> '", children=>{{id= > ' 2234 '}}]
Where the ID is a string, the number of digits is double digits (2, 4, 6, 8 ...). ), in addition to the 2-bit ID, the ID of the remaining digits always finds the previous ID (that is, element a:2234 must be able to find the element with ID 22 "i.e. left (0,len (A[id])-2)"
Although multiple traversal is possible, you want to achieve the following features:
1. Be able to organize correctly
2, after each organization, the original array will be reduced, such as the first time 2 bits are processed, then in the original array of ID bits of 2 is actually not necessary, all unset
Ask for advice AH ~
Reply to discussion (solution)
Set up a 2-D array Array[id][child] to traverse the original array once.
If a two-bit judgment is present, the insertion encounters a non-two-bit position and the child is placed where it is.
$a = Array (' 4401 ', ' xx ', ' 0001 ', ' 0002 ', ' n ', ' 2201 '), $b = Array (); for ($i = 0; $i < count ($a); $i + +) { if (strlen ($a [$i ] = = 2) { if (!array_key_exists ($a [$i], $b)) { $b [$a [$i]] = array (); } } else { $id = substr ($a [$i], 0, 2); if (Isset ($b [$id])) { if (!in_array ($a [$i], $b [$id]) {$b [$id] = $a [$i]; } } else { $b [$id] = array (); $b [$id] = $a [$i];} } Print_r ($b);
Yesterday's own code, the test can not be optimized, but after the use of found in the actual existence of problems, so give up this one-time read all the data and then organize the way back.
function Sort_dep ($deps) {//$step=2 the unordered dep into an ordered tree-like structure; $start =1; $res =array (); for ($start =1; $start <5; $start + +) {/ /cycle, that is, the data to be processed is foreach ($deps as $k + $v) {if (strlen ($v [' id ')] = = ($start * $step)) {PUT_DEP ($res, $v), unset ($deps [$ K]);}}} return $res;} Function Put_dep (& $res, $v) {//Put the array into $res $i=strlen ($v [' id ']), if ($i ==2) {$res []= $v;} else{//needs to find out what is under what $prefix=substr ($v [' id '],0, $i-2); foreach ($res as $key =>& $value) {if ($value [' id ']== $prefix ) {$value [' Children '][]= $v; Children need to set return true in front;}}}