我正在尝试删除我的多维数组的子数组,如果任何值为空,则删除整个子数组。我想要一个通用的功能!不想键入特定键。而不是ReIndex新形成的阵列。
我的数组就像
Array
(
[0] => Array
(
[name] => Test
[mobile] => 613594551
[email] => test@test.com
)
[1] => Array
(
[name] => Test1
[mobile] => 613594552
[email] => test2@test.com
)
[2] => Array
(
[name] => Test2
[mobile] => 613594553
[email] => test3@test.com
)
[3] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4@test.com
)
)
所以如果我的数组是
Array
(
[0] => Array
(
[name] =>
[mobile] => 613594551
[email] => test@test.com
)
[1] => Array
(
[name] => Test1
[mobile] =>
[email] => test2@test.com
)
[2] => Array
(
[name] => Test2
[mobile] => 613594553
[email] =>
)
[3] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4@test.com
)
)
比显示
Array
(
[0] => Array
(
[name] => Test3
[mobile] => 613594554
[email] => test4@test.com
)
)
答案 0 :(得分:2)
阐述Martin的答案,您可以对源数组和嵌套数组使用$filtered_array = array_filter($array, function($item){
return count($item) == count(array_filter($item));
});
sort($filtered_array); // to reindex
:
{{1}}
答案 1 :(得分:0)
使用array_filter()
迭代每个人的所有记录,并删除那些具有空值的记录。如果填写了所有记录,则array_filter()
之前和之后的记录数必须相等。如果他们没有使用unset()
删除此人。
请注意,此函数可以就地工作,因此它会修改原始数组。
<?php
$array = [
[
'name' => 'Test1',
'mobile' => 123456789,
'email' => null
], [
'name' => 'Test2',
'mobile' => 123456789,
'email' => 'test2@test.com'
], [
'name' => null,
'mobile' => 123456789,
'email' => 'test3@test.com'
],
];
function removeEmpty(&$arr) {
foreach ($arr as $index => $person) {
if (count($person) != count(array_filter($person, function($value) { return !!$value; }))) {
unset($arr[$index]);
}
}
}
removeEmpty($array);
print_r($array);
打印:
Array
(
[1] => Array
(
[name] => Test2
[mobile] => 123456789
[email] => test2@test.com
)
)
答案 2 :(得分:0)
假设数组项可能有不同的键:
$array = array(
0=>array('name'=>'','test'=>2),
1=>array('name'=>'sadad','test'=>2),
);
foreach($array as $index=>$item) {
$keys = array_keys($item); //here is the assumption
//you can define it before the foreach
//by checking the first array if YOU are 100% sure
//all items in the array have the same keys: name, mobile, email
foreach($keys as $key) {
if(empty($item[$key])) {
unset($array[$index]);
break;
}
}
}
var_dump($array);
输出:
array(1) {
[1]=>
array(2) {
["name"]=>
string(5) "sadad"
["test"]=>
int(2)
}
}