"Radiator","details"=>0=>["label"=>"Condition","value"=>"New",],1=>["">
假设我有一个如下所示的数组:
$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", ], ], ];
我想过滤这个数组,所以它只包含值不为空的详细信息。 Airco 的type
值为空,因此它不应返回详细的type
。在这种情况下,返回的数组应如下所示:
$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", ], ], ];
我知道我可以使用以下代码(如此处找到的)基于空列过滤数组:
$result = array_filter($array, function($o) use($column) { return trim( $o[$column] ) !== '' && $o[$column] !== null; });
但是由于我有一个嵌套数组details
,我不太确定如何调整此代码以使其适合我的情况。
您的
array_filter
仅在第一级起作用。您还希望在details
数组上进行循环,您可以使用简单的 foreach 循环来完成此操作。外部循环将遍历所有行,内部循环将遍历每行的详细信息
。现场演示