Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamimmoeen/d1a6792c7da4c03e86e66b7ac4b1e9d8 to your computer and use it in GitHub Desktop.
Save shamimmoeen/d1a6792c7da4c03e86e66b7ac4b1e9d8 to your computer and use it in GitHub Desktop.
In multidimensional array replace parent element value from child arrays
<?php
/**
* Stackoverflow link https://stackoverflow.com/questions/52388607/in-multidimensional-array-replace-parent-element-value-from-child-arrays
*/
$tree = array(
'16' => array(
'id' => '16',
'name' => 'Clothing',
'count' => '0',
'parent_id' => '0',
'children' => array(
'17' => array(
'id' => '17',
'name' => 'Tshirts',
'count' => '5',
'parent_id' => '16',
),
'18' => array(
'id' => '18',
'name' => 'Hoodies',
'count' => '3',
'parent_id' => '16',
),
'19' => array(
'id' => '19',
'name' => 'Accessories',
'count' => '0',
'parent_id' => '16',
'children' => array(
'31' => array(
'id' => '31',
'name' => 'Hats',
'count' => '2',
'parent_id' => '19',
),
'32' => array(
'id' => '32',
'name' => 'Belts',
'count' => '2',
'parent_id' => '19',
'children' => array(
'36' => array(
'id' => '36',
'name' => 'Sub Item',
'count' => '4',
'parent_id' => '32',
),
),
),
),
),
),
),
'20' => array(
'id' => '20',
'name' => 'Music',
'count' => '2',
'parent_id' => '0',
),
'21' => array(
'id' => '21',
'name' => 'Decor',
'count' => '3',
'parent_id' => '0',
),
);
function modify_tree($tree) {
$array_iterator = new RecursiveArrayIterator($tree);
$recursive_iterator = new RecursiveIteratorIterator($array_iterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($recursive_iterator as $key => $value) {
if (is_array($value) && array_key_exists('children', $value)) {
$array_with_children = $value;
$array_with_children_count = $array_with_children['count'];
foreach ($array_with_children['children'] as $children) {
$array_with_children_count = $array_with_children_count + $children['count'];
}
$array_with_children['count'] = $array_with_children_count;
$current_depth = $recursive_iterator->getDepth();
for ($sub_depth = $current_depth; $sub_depth >= 0; $sub_depth--) {
// Get the current level iterator
$sub_iterator = $recursive_iterator->getSubIterator($sub_depth);
// If we are on the level we want to change, use the replacements
// ($array_with_children) other wise set the key to the parent
// iterators value
if ($sub_depth === $current_depth) {
$value = $array_with_children;
} else {
$value = $recursive_iterator->getSubIterator(($sub_depth + 1))->getArrayCopy();
}
$sub_iterator->offsetSet($sub_iterator->key(), $value);
}
}
}
return $recursive_iterator->getArrayCopy();
}
$modified_tree = modify_tree($tree);
echo '<pre>';
print_r($modified_tree);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment