Suppose I have an array like this:
$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", ], ], ];
I want to filter this array so it only contains details where the value is not empty. Airco's type
value is empty, so it should not return detailed type
. In this case, the returned array should look like this:
$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", ], ], ];
I know I can filter an array based on empty columns using the following code (as found here):
$result = array_filter($array, function($o) use($column) { return trim( $o[$column] ) !== '' && $o[$column] !== null; });
But since I have a nested arraydetails
, I'm not quite sure how to adjust this code to make it work for my case.
P粉4587250402023-09-09 09:24:13
Your array_filter
only works on the first level. You also want to loop over the details
array, you can do this using a simple foreach loop. The outer loop will iterate through all the rows, and the inner loop will iterate over the details
of each row.
<?php foreach($array as &$row){ foreach($row['details'] as $key => $record){ if(strlen($record['value']) == 0){ unset($row['details'][$key]); } } }