我有一个数组,但我不知道如何删除所有空的'subs'
子数组。
Array
(
[3] => Array
(
[sponsorid] => 2
[user_id] => 3
[subs] => Array
(
[4] => Array
(
[sponsorid] => 3
[user_id] => 4
[subs] => Array
(
[5] => Array
(
[sponsorid] => 4
[user_id] => 5
[subs] => Array
(
[6] => Array
(
[sponsorid] => 5
[user_id] => 6
[subs] => Array()
)
[9] => Array
(
[sponsorid] => 5
[user_id] => 9
[subs] => Array()
)
[10] => Array
(
[sponsorid] => 5
[user_id] => 10
[subs] => Array()
)
)
)
[12] => Array
(
[sponsorid] => 4
[user_id] => 12
[subs] => Array()
)
)
)
[11] => Array
(
[sponsorid] => 3
[user_id] => 11
[subs] => Array()
)
)
)
)
答案 0 :(得分:0)
递归是必要的,因为底层子阵列具有可变深度。
代码:(Demo)
function removeEmptySubs($array){
foreach ($array as &$a){ // make $a modifiable by reference
if(!sizeof($a['subs'])){ // check if 'subs' array is empty
unset($a['subs']); // remove it
}else{
$a['subs']=removeEmptySubs($a['subs']); // recurse
}
}
return $array;
}
$array=[
3 => [
'sponsorid' => 2,
'user_id' => 3,
'subs' => [
4 => [
'sponsorid' => 3,
'user_id' => 4,
'subs' => [
5 => [
'sponsorid' => 4,
'user_id' => 5,
'subs' => [
6 => [
'sponsorid' => 5,
'user_id' => 6,
'subs' => [
]
],
9 => [
'sponsorid' => 5,
'user_id' => 9,
'subs' => [
]
],
10 => [
'sponsorid' => 5,
'user_id' => 10,
'subs' => [
]
]
]
],
12 => [
'sponsorid' => 4,
'user_id' => 12,
'subs' => [
]
]
]
],
11 => [
'sponsorid' => 3,
'user_id' => 11,
'subs' => [
]
]
]
]
];
var_export(removeEmptySubs($array));
输出:
array (
3 =>
array (
'sponsorid' => 2,
'user_id' => 3,
'subs' =>
array (
4 =>
array (
'sponsorid' => 3,
'user_id' => 4,
'subs' =>
array (
5 =>
array (
'sponsorid' => 4,
'user_id' => 5,
'subs' =>
array (
6 =>
array (
'sponsorid' => 5,
'user_id' => 6,
),
9 =>
array (
'sponsorid' => 5,
'user_id' => 9,
),
10 =>
array (
'sponsorid' => 5,
'user_id' => 10,
),
),
),
12 =>
array (
'sponsorid' => 4,
'user_id' => 12,
),
),
),
11 =>
array (
'sponsorid' => 3,
'user_id' => 11,
),
),
),
)