1

如何删除状态等于 0 的所有数组条目?

这意味着:$array[1][3];$array[4];

Array
(
    [1] => Array
        (
            [id] => 1
            [parent_id] => 0
            [status] => 2
            [title] => bananer
            [breadcrumb] => /bananer
            [slug] => /bananer
            [2] => Array
                (
                    [id] => 2
                    [parent_id] => 1
                    [status] => 2
                    [title] => sub bananer
                    [breadcrumb] => /bananer/sub bananer
                    [slug] => /bananer/sub-bananer
                )
            [3] => Array
                (
                    [id] => 3
                    [parent_id] => 1
                    [status] => 0
                    [title] => sub bananer 2
                    [breadcrumb] => /bananer/sub bananer 2
                    [slug] => /bananer/sub-bananer-2
                )
        )
    [4] => Array
        (
            [id] => 4
            [parent_id] => 0
            [status] => 0
            [title] => appelsin
            [breadcrumb] => /appelsin
            [slug] => /appelsin
            [5] => Array
                (
                    [id] => 5
                    [parent_id] => 4
                    [status] => 2
                    [title] => sub appelsin
                    [breadcrumb] => /appelsin/sub appelsin
                    [slug] => /appelsin/sub-appelsin
                )
            [6] => Array
                (
                    [id] => 6
                    [parent_id] => 4
                    [status] => 2
                    [title] => sub appelsin 2
                    [breadcrumb] => /appelsin/sub appelsin 2
                    [slug] => /appelsin/sub-appelsin-2
                )
        )
)
4

3 回答 3

0

这样的事情可能会有所帮助

function parse($var)
{
    foreach($var as $key => $val)
    {
        if( is_array($val) )
        {
            parse($val)
        }
        else
        {
            if($key == 'status' && $val ==0 )
            {
                // do something here
            }
        }
    }
}
于 2012-11-10T23:46:18.387 回答
0

试试这个:

function deleteIt(&$array)
{
    foreach($array as $key => &$value)
    {
        if (is_numeric($key)) deleteIt($value);
        if (isset($value['status']) && !$value['status']) unset($array[$key]);
    }
}

这会在传递引用时递归地遍历数组,以便在删除时修改原始数组。注意函数原型和&.deleteItforeach

于 2012-11-10T23:46:57.773 回答
0

您可以做一些高度专业化的事情,例如:

function stripBadStatus($array) {
foreach($array as $k=>$arr) {
    if($arr['status'] == 0) {
        unset($array[$k]);
    } else if(is_array($arr)) {
        foreach($arr as $deepk=>$deeparr) {
            if($deeparr['status'] == 0) {
                unset($array[$k][$deepk]);
            }
        }
    }
}

return $array;
}
于 2012-11-10T23:49:11.760 回答