Let’s imagine we have this multidimensional array which contains nested arrays
$arr = [
1 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
2 => [
'id' => 1,
'families' => [
0 => [
'id' => 2,
'products' => [
1 => 'John Doe'
],
],
1 => [
'id' => 3,
'products' => [],
],
]
],
3 => [
'id' => 1,
'products' => [
1 => 'Hi',
2 => 'Hello',
]
],
4 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
];
I need to keep all ancestors and descendants where there is at least one item in the key “products”, all other arrays should be unset.
So, in this particular example, the result should be as follows:
$arr = [
2 => [
'id' => 1,
'families' => [
0 => [
'id' => 2,
'products' => [
1 => 'John Doe'
],
],
]
],
3 => [
'id' => 1,
'products' => [
1 => 'Hi',
2 => 'Hello',
]
],
];
Basically, what needs to be done is to go from the most inner array up and asking:
-
Is our key “products” empty? Yes
-
Is our key “families” either empty or not set? Yes
-
unset this array
Any help is appreciated!