我有这个多维数组,如果[earnings]
索引为空,我想完全删除。
Array
(
[0] => Array
(
[earnings] =>
[other] => Array()
[ord] => 2
[days] => 1
[total] => 1
)
[1] => Array
(
[earnings] => The campaign was effectively ended in November 1917.
[other] => Array
(
[campaign] => 1
[novemb] => 1
[today] => 1
)
[ord] => 1
[days] => 8
[total] => 1
)
)
我想输出这样的东西:
[1] => Array
(
[earnings] => The campaign was effectively ended in November 1917.
[other] => Array
(
[campaign] => 1
[novemb] => 1
[today] => 1
)
[ord] => 1
[days] => 8
[total] => 1
)
我试过这个,但不能很好地运作:
foreach($array as $key=>$test){
foreach($test as $koval=>$user) {
if( empty($user['earnings']) || !file_exists($staff['earnings'])) {
unset($array[$key][$koval]); }}}
答案 0 :(得分:2)
$array = array_filter($array,function($item) {
return (!empty($item['earnings']));
});
答案 1 :(得分:1)
您循环播放次数太多次了。你想要的是这个:
foreach($array as $i => $item) {
if(empty($item['earnings'])) {
unset($array[$i]);
}
}
你应该看看下面的FuzzyTree的答案,以便更清洁地做到这一点。
答案 2 :(得分:0)
您要找的是array_filter
http://php.net/manual/en/function.array-filter.php
$arr = array(
array(
'earnings' => null,
'other' => array(),
'ord' => 2,
'days' => 1,
'total' => 1,
),
array(
'earnings' => 'The campaign was effectively ended in November 1917.',
'other' => array(
'campaign' => 1,
'novemb' => 1,
'today' => 1,
),
'ord' => 1,
'days' => 8,
'total' => 1,
),
);
var_dump($arr);
//array(2) {
// [0] =>
// array(5) {
// 'earnings' =>
// NULL
// 'other' =>
// array(0) {
// }
// 'ord' =>
// int(2)
// 'days' =>
// int(1)
// 'total' =>
// int(1)
// }
// [1] =>
// array(5) {
// 'earnings' =>
// string(52) "The campaign was effectively ended in November 1917."
// 'other' =>
// array(3) {
// 'campaign' =>
// int(1)
// 'novemb' =>
// int(1)
// 'today' =>
// int(1)
// }
// 'ord' =>
// int(1)
// 'days' =>
// int(8)
// 'total' =>
// int(1)
// }
//}
$filtered = array_filter($arr, function ($val) {
return isset($val['earnings']) && !empty($val['earnings']);
});
var_dump($filtered);
//array(1) {
// [1] =>
// array(5) {
// 'earnings' =>
// string(52) "The campaign was effectively ended in November 1917."
// 'other' =>
// array(3) {
// 'campaign' =>
// int(1)
// 'novemb' =>
// int(1)
// 'today' =>
// int(1)
// }
// 'ord' =>
// int(1)
// 'days' =>
// int(8)
// 'total' =>
// int(1)
// }
//}