Let’s say I have an array that looks 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 includes details where the value is not empty. The value for type
of Airco is empty, so it should not return the detail type
. The returned array should in this case 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 an empty column with the following code (as found here):
$result = array_filter($array, function($o) use($column) {
return trim( $o[$column] ) !== '' && $o[$column] !== null;
});
but as I have a nested array details
I’m not quite sure how to adapt this code so it works for my case.
3
Answers
Try this and will resolved the problem
New Array Output
You can use
array_map
andarray_filter
to acomplish this:Above code will remove 3rd array from
Radiator
, 2nd array fromAirco
and 3rd array fromRefrigerator
that have empty values forlabel
,value
or both.Your
array_filter
is only working on the first level. You would rather want to loop ondetails
array too, which you can do using simple foreach loops. The outer loop will loop over all rows and the inner one overdetails
of each row.Live Demo