Reputation: 5471
I was wondering if anyone could help me out, I have a multidimensional array and I need the values removed if they're empty (well, set to 0). Here's my array:
Array
(
[83] => Array
(
[ctns] => 0
[units] => 1
)
[244] => Array
(
[ctns] => 0
[units] => 0
)
[594] => Array
(
[ctns] => 0
)
)
And I want to only be left with:
Array
(
[83] => Array
(
[units] => 1
)
)
If anyone could help me, that would be fantastic! :)
Upvotes: 0
Views: 411
Reputation: 82028
Looks like you need tree traversal:
function remove_empties( array &$arr )
{
$removals = array();
foreach( $arr as $key => &$value )
{
if( is_array( $value ) )
{
remove_empties( $value ); // SICP would be so proud!
if( !count( $value ) ) $removals[] = $key;
}
elseif( !$value ) $removals[] = $key;
}
foreach( $removals as $remove )
{
unset( $arr[ $remove ] );
}
}
Upvotes: 1
Reputation: 16091
this will help you:
Remove empty items from a multidimensional array in PHP
Edit:
function array_non_empty_items($input) {
// If it is an element, then just return it
if (!is_array($input)) {
return $input;
}
$non_empty_items = array();
foreach ($input as $key => $value) {
// Ignore empty cells
if($value) {
// Use recursion to evaluate cells
$items = array_non_empty_items($value);
if($items)
$non_empty_items[$key] = $items;
}
}
// Finally return the array without empty items
if (count($non_empty_items) > 0)
return $non_empty_items;
else
return false;
}
Upvotes: 1