private function extractSubCategories($categories)
{
$result = [];
foreach ($categories as $key => $node) {
if (empty($node['sub_categories'])) {
$result[$node['id']] = $node;
} else {
$tmp = $node['sub_categories'];
unset($node['sub_categories']);
$result[$node['id']] = $node;
$child = $this->extractSubCategories($tmp);
$result = $result + $child;
}
}
return $result;
}
More detail ...
Damn it! Simple change array_merge to '+'
// Second way
// foreach ($debug as $key => $node) {
// if (empty($node['sub_categories'])) {
// $result[$node['id']] = $node;
// } else {
// $secondStep = $secondStep + $node['sub_categories'];
// }
// }
// // dd($result);
// dd($secondStep);
manually many steps.
$debug = array_slice($data, 0, 7, true);
// dd($debug);
// echo '<pre>'. var_export($debug) . '</pre>';
// $result = $this->extractSubCategories($debug);
slice($data, 0, 3, true) vs $data['1'] since its key retain.
JSON tree bonsai sample:
"22":{
"id":"22",
"title":"OEM Rotor",
"caption":"OEM Rotor",
"parentId":"1",
"sub_categories":[
],
"childCount":0
},
"23":{
"id":"23",
"title":"Drilled Rotor",
"caption":"Drilled Rotor",
"parentId":"1",
"sub_categories":[
],
"childCount":0
}
}
Code convert nested tree array to plain array (used for Bonsai JSON)
Recursive function;
private function extractSubCategories($categories)
{
$result = [];
foreach ($categories as $key => $node) {
if (empty($node['sub_categories'])) {
$result[$node['id']] = $node;
} else {
$tmp = $node['sub_categories'];
unset($node['sub_categories']);
$result[$node['id']] = $node;
$child = $this->extractSubCategories($tmp);
$result = $result + $child; // array_merge not work, it lost array keys
}
}
return $result;
}
Nested PHP array look like:
Array
(
[1] => Array
(
[id] => 1
[title] => eLINE Brake Rotors
[caption] => eLINE Series Brake Rotors
[parentId] =>
[sub_categories] => Array
(
[22] => Array
(
[id] => 22
[title] => OEM Rotor
[caption] => OEM Rotor
[parentId] => 1
[sub_categories] => Array
(
)
[childCount] => 0
)
[23] => Array
(
[id] => 23
[title] => Drilled Rotor
[caption] => Drilled Rotor
[parentId] => 1
[sub_categories] => Array
(
)
[childCount] => 0
)
)...
)
Comments
Post a Comment