如何基于嵌套数组的value列过滤PHP多维数组?
过滤PHP多维数组中嵌套details的空value项
给定如下PHP多维数组:
$array = [ 0 => [ "label" => "Radiator", "details" => [ 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ], 1 => [ "label" => "Airco", "details" => [ 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "", ], ], ], 2 => [ "label" => "Refrigerator", "details" => [ 0 => [ "label" => "Condition", "value" => "Bad", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ], ];
需要过滤掉details中value为空(含空白字符)的子项,最终得到如下结果:
$array = [ 0 => [ "label" => "Radiator", "details" => [ 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ], 1 => [ "label" => "Airco", "details" => [ 0 => [ "label" => "Condition", "value" => "New", ], ], ], 2 => [ "label" => "Refrigerator", "details" => [ 0 => [ "label" => "Condition", "value" => "Bad", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ], ];
你之前了解的单层数组过滤逻辑需要调整,因为这里存在嵌套结构。可以通过遍历外层数组,对每个元素的details子数组单独应用过滤逻辑来实现:
// 遍历外层数组,处理每个设备项 $result = array_map(function($item) { // 过滤details数组,保留value非空的子项 $item['details'] = array_filter($item['details'], function($detail) { return trim($detail['value']) !== '' && $detail['value'] !== null; }); return $item; }, $array); // 可选:重置details的索引为连续数字,避免过滤后出现断号 foreach ($result as &$item) { $item['details'] = array_values($item['details']); } unset($item); // 释放引用
代码说明
- 用
array_map遍历外层数组的每个设备项,确保原有的label等字段完整保留 - 对每个设备的
details数组,用array_filter筛选出value经过trim后不为空字符串且不为null的子项 - 最后的
array_values操作是可选的,用来把过滤后的details数组重置为连续数字索引,避免出现断号的情况
内容的提问来源于stack exchange,提问作者Senne Vandenputte
相关产品推荐
相关产品推荐

