我有一个结构如下的数组:
$something = array(
0 => array(
'label' => 'Foo',
'items' => array(
'123' => 4,
'124' => 0,
)
),
1 => array(
'label' => 'Bar',
'items' => array(
'125' => 5,
'126' => 1,
)
),
2 => array(
'label' => 'Baz',
'items' => array(
'127' => 0,
'128' => 0,
)
)
);
我需要删除所有值为零的“items”键,如果一个项目没有子项,则删除整个 block 。
因此,在过滤该数组后,我应该:
array(2){
[0]=>
array(2) {
["label"]=> "Foo"
["items"]=>
array(1) {
[123]=> 4
}
}
[1]=>
array(2) {
["label"]=> "Bar"
["items"]=>
array(2) {
[125]=> 5
[126]=> 1
}
}
}
我已经尝试使用 array_filter、array_walk 和 array_walk_recursive(这个效果很好 - 但是 - 不允许我删除回调函数中的键..)但没有成功..
我必须在一个新数组中解构和重建,还是我错过了 array_* 函数的正确用法?
最佳答案
$something = array( .. ); // as defined above
for ( $i = 0, $iMax = count( $something ); $i < $iMax; $i++ )
{
foreach ( $something[$i]['items'] as $key => $value )
{
if ( !$value )
unset( $something[$i]['items'][$key] );
}
if ( count( $something[$i]['items'] ) == 0 )
unset( $something[$i] );
}
$something = array_values( $something ); // reset indices
关于php - 如何过滤数组以删除 child 为零的 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191372/