I have an associative array: $csv_arr
Array
(
[0] => Array
(
[Enfalac] => alpha linolenic acid 300 mg
[Enfapro] => alpha linolenic acid 200 mg
)
[1] => Array
(
[Enfalac] => arachidonic acid 170 mg
[Enfapro] =>
)
[2] => Array
(
[Enfalac] =>
[Enfapro] =>
)
[3] => Array
(
[Enfalac] => calcium 410 mg
[Enfapro] => calcium 550 mg
)
)
How can I remove all completely empty entries such as $csv_arr[2]
but preserve partial entries such as $csv_arr[1]
I've tried $csv_arr = array_filter(array_map('array_filter', $csv_arr));
but this removes the empty element: $csv_arr[1]['Enfapro']
Thx
Try this, a little weird, but :
array_filter($csv_arr, function($v){return array_filter($v) == array();});
Completely untested and I don't remember if this is the proper syntax or not for closures, but it could work.
Edit (tested and working):
<?php
$csv_arr = array(
0 => array(
'Enfalac' => 'alpha linolenic acid 300 mg',
'Enfapro' => 'alpha linolenic acid 200 mg'
),
1 => array(
'Enfalac' => 'arachidonic acid 170 mg',
'Enfapro' => ''
),
2 => array(
'Enfalac' => '',
'Enfapro' => ''
),
3 => array(
'Enfalac' => 'calcium 410 mg',
'Enfapro' => 'calcium 550 mg'
)
);
$c = function($v){
return array_filter($v) != array();
};
var_dump(array_filter($csv_arr, $c));
?>
OK, thanks for the help everyone. I managed to do it like this in a loop.
if(implode('',$csv_arr[$i])==''){
unset($csv_arr[$i]);
}
I think this is the better and appropriate solution for this,
here is the code:
$arr[0]['id'] = "id1";
$arr[0]['name'] = "testing";
$arr[1]['id'] = "id2";
$arr[1]['name'] = "another";
$arr[2]['id'] = "";
$arr[2]['name'] = "";
$d = array_keys($arr);
foreach($arr as $key=>$values){
$a = array_keys($values);
$n = count($a);
for($i=0,$count=0;$i<$n;$i++){
if($values[$a[$i]]==NULL){
$count++;
}
}
if($count==$n){
unset($arr[$key]);
}
}
echo "<pre>";
print_r($arr);
If you want this to work for more nested associative arrays, you can implement same in recursive function.
Thanks,
Nirav