0

我想过滤多维数组的一部分。我已经使用了该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);
}

但是,在之后打印数组时,数组并没有改变。

4

2 回答 2

1

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

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

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

演示!

于 2013-11-14T16:35:28.357 回答
0

foreach 构造会在您迭代数组的每个部分时对其进行复制。您必须显式调用原始数组来编辑它:

$posted_product_details[$column]['data'] = array_filter($data);
于 2013-11-14T16:40:01.137 回答