Reputation: 2207
I have an multidimensional array (key - value), and some values are not set, empty in this case, if so the parent array must be removed from the main array.
The code that I have build only removes the empty key.
In my example the IT & ES language translation keys are empty so we need to removed this parent array.
$results = $arr =array(
[16] => Array
(
[0] => Array
(
[language] => de
[translation] => blog/beer
)
[1] => Array
(
[language] => en
[translation] => blog/some-slug-yeah
)
[2] => Array
(
[language] => es
[translation] =>
)
[3] => Array
(
[language] => fr
[translation] => blog/paris-big-city
)
[4] => Array
(
[language] => it
[translation] =>
)
[5] => Array
(
[language] => nl
[translation] => blog/nederlands-slug
)
)
[...]//more
)
Function to remove keys.
function array_filter_recursive($input){
foreach ($input as &$value){
if (is_array($value)){
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
$results = array_filter_recursive( $results );
Upvotes: 0
Views: 76
Reputation: 26153
If the array always has 2 levels, you don't need recursion.
function array_filter_recursive($input){
foreach ($input as &$value){
$value = array_filter($value, function($x) { return !empty($x['translation']); });
}
return $input;
}
Upvotes: 1
Reputation: 377
If your structure is always going to be like this:
$arr = (
[0] => Array
(
[language] => de
[translation] => blog/beer
)
[1] => Array
(
[language] => en
[translation] => blog/some-slug-yeah
)
you can do this:
for($i = 0; $i < count($arr); $i++}
if(!isset($arr[$i]["translation"]){
unset($arr[$i])
}
}
//re-index thee array;
$arr = array_values($arr);
Upvotes: 0