How can I organize a one-dimensional array into a "tree" array ...... The name of the problem is a bit confusing ...... Input an array: [{id = & gt; '00'}, {id = & gt; '01'}, {id = & gt; '22 '}, {id = '000000'}, {id = & gt; '000000'}] now you want to organize this array into a "tree" array.
Okay ...... The name of the problem is a bit confusing ......
Input arrays are as follows:
[{id=>'00'},
{id=>'01'},
{id=>'22'},
{id='0001'},
{id=>'2234'}]
Now you want to organize this array in the following form:
[
{id=>'00',children=>{{id=>'0001'}} },
{id=>'01',children=>{} },
{id=>'22',children=>{{id=>'2234'}} }
]
The id is a string and the number of digits is double (2, 4, 6, 8 ......), Except for the two-digit id, the IDs of the other digits can always find the upper-level id (that is, the element A: 2234 must be able to find the id of 22 [that is, left (0, len (A [id])-2)] elements
Although multiple traversal is also feasible, the following functions can be implemented:
1. correct organization
2. after each organization, the original array will be reduced. for example, if two digits are processed for the first time, there is no need to set the id bit to 2 in the original array, all unset
Ask for advice ~
------ Solution --------------------
Create a two-dimensional array [id] [child] to traverse the original array once.
If two operators are used to determine whether the existence or absence of a condition exists, if two operators are inserted, the system considers the child as the place to be put.
$a = array('4401','00','0001','0002','22','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);