[英]Filter part of multidimensional array
I would like to filter part of a multidimensional array. 我想过滤多维数组的一部分。 I have used the
array_filter
function. 我已经使用了
array_filter
函数。 When I print the filtered data, it shows correctly, but I can't seem to save the data back to the array. 当我打印过滤后的数据时,它可以正确显示,但是似乎无法将数据保存回阵列中。
Here is the multidimensional array (called $posted_product_details
) beforehand, containing the internal array ( [data]
) which I would like 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] =>
)
)
)
Here I attempt to loop through the array and filter the data: 在这里,我尝试遍历数组并过滤数据:
foreach ($posted_product_details as $column => $info) {
$name = $info['name'];
$data = $info['data'];
$info['data'] = array_filter($data);
}
However, upon printing the array afterward, the array has not changed. 但是,在随后打印阵列时,该阵列没有更改。
Pass the value by reference to modify the original array: 通过引用传递值以修改原始数组:
foreach ($posted_product_details as $column => & $info) {
$name = $info['name'];
$data = $info['data'];
$info['data'] = array_filter($data);
}
This will correctly filter the data
part of your array. 这将正确过滤数组的
data
部分。 However, if you need to filter out deeper elements, you'll have to use a recursive function, such as this one . 但是,如果您需要过滤掉更深层的元素,则必须使用一个递归函数,例如this 。
The foreach construct makes a copy of each piece of the array as you iterate over it. 在遍历数组时,foreach构造会复制数组的每个部分。 You have to explicitly call the original array to edit it:
您必须显式调用原始数组进行编辑:
$posted_product_details[$column]['data'] = array_filter($data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.