php - 如何过滤数组以删除 child 为零的 parent ?

标签 php arrays

我有一个结构如下的数组:

$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/

相关文章:

php - 如何使用php显示sql中开始日期和结束日期或开始时间和结束时间之间的数据?

javascript - 使用 JSON 从 PHP 到 Javascript 的 MySQL 数据

PHP XML 解析问题

javascript 迭代嵌套对象数组中的对象并按 ids 过滤并返回更新后的相同原始数据集

php - 如何使用Codeception验收助手?

php - 在侧边栏 Wordpress 小部件之间放置文本

arrays - 如何将数组中对象的属性分配给多个类属性?

python - Python 中的 8 Queens 解决方案

javascript - 从第一个索引中按顺序删除数组 javascript 值

c++ - 尝试使用 fstream : no match for 'operator<<' 将字符写入文件