删除多维数组的深层子数组中的空元素[重复]

问题描述 投票:0回答:2

我想过滤多维数组的一部分。我使用了

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);
}

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

php arrays multidimensional-array array-filter
2个回答
1
投票

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

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

这将正确过滤数组的

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

演示!


0
投票

当您迭代数组时,foreach 构造会为数组的每个部分创建一个副本。您必须显式调用原始数组才能对其进行编辑:

$posted_product_details[$column]['data'] = array_filter($data);
© www.soinside.com 2019 - 2024. All rights reserved.