过滤多维数组的一部分

时间:2013-11-14 16:34:02

标签: php multidimensional-array array-filter

我想过滤多维数组的一部分。我使用了array_filter函数。当我打印过滤后的数据时,它显示正确,但我似乎无法将数据保存回数组。

这是多维数组(前面称为$posted_product_details),包含我想要过滤的内部数组([data]):

Array
(
[column_1] => Array
    (
        [name] => Colour
        [data] => Array
            (
                [0] => Blue
                [1] => Green
                [2] => Red
                [3] => Yellow
                [4] => 
                [5] => 
                [6] => 
                [7] => 
                [8] => 
                [9] => 
            )

    )

[column_2] => Array
    (
        [name] => Pack QTY
        [data] => Array
            (
                [0] => 3
                [1] => 3
                [2] => 3
                [3] => 3
                [4] => 
                [5] => 
                [6] => 
                [7] => 
                [8] => 
                [9] => 
            )

    )

[column_3] => Array
    (
        [name] => Product Code
        [data] => Array
            (
                [0] => 65030
                [1] => 65029
                [2] => 65028
                [3] => 65031
                [4] => 
                [5] => 
                [6] => 
                [7] => 
                [8] => 
                [9] => 
            )

    )

[column_4] => Array
    (
        [name] => Barcode
        [data] => Array
            (
                [0] => 5099570650307
                [1] => 5099570650291
                [2] => 5099570650284
                [3] => 5099570650314
                [4] => 
                [5] => 
                [6] => 
                [7] => 
                [8] => 
                [9] => 
            )

    )

[column_5] => Array
    (
        [name] => 
        [data] => Array
            (
                [0] => 
                [1] => 
                [2] => 
                [3] => 
                [4] => 
                [5] => 
                [6] => 
                [7] => 
                [8] => 
                [9] => 
            )

    )

)

这里我尝试遍历数组并过滤数据:

foreach ($posted_product_details as $column => $info) {
    $name = $info['name'];
    $data = $info['data'];
    $info['data'] = array_filter($data);
}

然而,在之后打印数组时,数组没有改变。

2 个答案:

答案 0 :(得分:1)

通过引用传递值来修改原始数组:

foreach ($posted_product_details as $column => & $info) {
    $name = $info['name'];
    $data = $info['data'];
    $info['data'] = array_filter($data);
}

这将正确过滤数组的data部分。但是,如果您需要过滤掉更深层的元素,则必须使用递归函数,例如this one

Demo!

答案 1 :(得分:0)

当你迭代它时,foreach构造会复制每个数组。您必须显式调用原始数组进行编辑:

$posted_product_details[$column]['data'] = array_filter($data);