'trying to restructure an array so child arrays appear under parents array [duplicate]
I have an array that looks something like:
$someArray = array(
array(
"id"=> 1,
"name"=> "somename1",
"parent"=> 0
),
array(
"id"=> 53,
"name"=> "somename2",
"parent"=> 1
),
array(
"id"=> 921,
"name"=> "somename3",
"parent"=> 53,
)
.
.
.
.
.
.
);
Of course, there are more cells in the array this is just a small portion.
I am trying to turn this array to something like:
$someArray = array(
array(
"id"=> 1,
"name"=> "somename1",
"parent"=> 0,
"children" => array(
array(
"id"=> 53,
"name"=> "somename2",
"parent"=> 1,
"children" => array(
array(
"id"=> 921,
"name"=> "somename3",
"parent"=> 53,
"children" => array(
)
)
)
)
)
)
.
.
.
.
.
.
);
Solution 1:[1]
/*
Gets reversed array,
Returns multidimensional tree array.
*/
function buildTree($parts) {
if (count($parts) == 1) {
return $parts[0];
}
$last_item = array_pop($parts);
$last_item[] = buildTree($parts);
return $last_item;
}
Testing:
$parts = array(
array('1','2','3',5),
array('3','8','3',1),
array('1', 5,'2','3'),
array('D','2','3',5),
array('A','2','3',5)
);
var_dump(buildTree(array_reverse($parts)));
Output:
array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(5) {
[0]=> string(1) "3" [1]=> string(1) "8" [2]=> string(1) "3" [3]=> int(1) [4]=> array(5) {
[0]=> string(1) "1" [1]=> int(5) [2]=> string(1) "2" [3]=> string(1) "3" [4]=> array(5) {
[0]=> string(1) "D" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(4) {
[0]=> string(1) "A" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5)
} } } } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yam Mesicka |
