Reputation: 1
My multi-dimensional array looks like this:
Array
(
[0] => Array
(
[0] => 2010-12-03
[1] => 0
[2] => Array
(
[0] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[1] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[2] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[3] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[5] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
)
)
[1] => Array
(
[0] => 2010-12-10
[1] => 486
[2] => Array
(
[0] => Array
(
[0] => Bob
[1] => Lucy
[2] => 54
[3] => Y
[4] => PC1Clean
)
[1] => Array
(
[0] => Jo
[1] => Mary
[2] => 432
[3] => Y
[4] => PC2Bar
)
[2] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[3] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
[5] => Array
(
[0] =>
[1] =>
[2] => 0
[3] =>
[4] =>
)
)
)
I've tried array_filter
and different loop iterations to remove the zero
/null
values, such as
function removeElementWithValue($array, $key, $value) {
foreach($array as $subKey => $subArray) {
if($subArray[$key] == $value) {
unset($array[$subKey]);
}
}
}
But nothing seems to be working. Any help would be much appreciated!
Upvotes: 0
Views: 189
Reputation: 2335
Maybe this answer is a bit too late, but here it is:
$array = array( // array with examples
array('123',' 456', array(123, null)),
array('', null, '123'),
123,
234,
0,
null,
);
$filterEmptyValues = function($val) use (&$filterEmptyValues) {
foreach($val as $key => $value) {
if (!is_array($value)) {
if (!$value) unset($val[$key]);
}
else $val[$key] = call_user_func($filterEmptyValues, $value);
}
return $val;
};
$array = $filterEmptyValues($array) ;
print_r($array);
Upvotes: 0
Reputation: 39542
You need to recursively call your remove function. (Call the function for every sub-value in the array, and then the function will call itself for every sub-sub-value etc. automatically until it can't get any further down the tree).
Here's a quickly made (untested) function that should remove all empty values (including arrays, if they're empty):
function removeEmptyElements($array) {
foreach ($array as $key => $value){
if (empty($value)) {
unset($array[$key]);
} else if (is_array($value)) {
$array[$key] = removeEmptyElements($value);
}
}
return $array;
}
Upvotes: 3