i have a problem with my multidimensional array. I want to remove some items from child array by $id value.
here is my multidimensional example array and selectedIds:
$myArray = [ ['id' => '2', 'name' => 'Punk' ],[ 'id' => '5', 'name' => 'Rock', 'children' => [ '30' => ['id' => '30', 'name' => 'Hard Rock', 'parentId' => '5' ], '40' => ['id' => '40', 'name' => 'Soft Rock', 'parentId' => '5' ], '50' => ['id' => '50', 'name' => 'Glam Rock', 'parentId' => '5' ] ] ] ]; $selectedIds = [2,5,30];
and i want to remove from array those items which are not in selectedIds array.
so i want to have output:
$outputArray = [ [ 'id' => '2', 'name' => 'Punk' ],[ 'id' => '5', 'name' => 'Rock', 'children' => [ '30' => ['id' => '30', 'name' => 'Hard Rock', 'parentId' => '5'] ] ] ];
i try to make it with foreach and array_key_exist but its not correct:
foreach ($myArray as $key=>$value) { if (array_key_exists('children', $value)) { foreach ($selectedIds as $id) { if (isset($value['children'][$id])) { $outputArray[] = $value['children'][$id]; } } } } print_r($outputArray);
this outpus is only item with id 30
Advertisement
Answer
write else part
into your code if array has no children key
else{ foreach ($selectedIds as $id) { if ($value['id'] == $id) { $outputArray[$key] = $value; } } }
Final code
<?PHP $myArray = [ [ 'id' => '2', 'name' => 'Punk' ], [ 'id' => '5', 'name' => 'Rock', 'children' => [ '30' => ['id' => '30', 'name' => 'Hard Rock', 'parentId' => '5' ], '40' => ['id' => '40', 'name' => 'Soft Rock', 'parentId' => '5' ], '50' => ['id' => '50', 'name' => 'Glam Rock', 'parentId' => '5' ] ] ] ]; $selectedIds = [2,5,30]; foreach ($myArray as $key=>$value) { if (array_key_exists('children', $value)) { foreach ($selectedIds as $id) { if (isset($value['children'][$id])) { $outputArray[$key]['id'] = $value['id']; $outputArray[$key]['name'] = $value['name']; $outputArray[$key]['children'][$id] = $value['children'][$id]; } } }else{ foreach ($selectedIds as $id) { if ($value['id'] == $id) { $outputArray[$key] = $value; } } } } echo "<pre>"; print_r($outputArray); ?>
Output
Array ( [0] => Array ( [id] => 2 [name] => Punk ) [1] => Array ( [id] => 5 [name] => Rock [children] => Array ( [30] => Array ( [id] => 30 [name] => Hard Rock [parentId] => 5 ) ) ) )