Reputation: 432
So my output is something like this, but can vary:
{
"4": {
"position": "0",
"type_id": "1",
"miles": "0",
"drop_hooks": "0",
"different": "off"
},
"8": {
"position": "1",
"type_id": "3",
"miles": "0",
"drop_hooks": "0",
"tray_count": "0",
"roll_offs": "0",
"pack_outs": "0",
"different": "off"
}
}
How can I remove (unset) any item (miles
, drop_hooks
, tray_count
, etc) that is equal to zero?
Note: Sometimes position
can be zero. I do not want to remove/unset position
from the collection.
Edit: Desired Result:
{
"4": {
"position": "0",
"type_id": "1",
"different": "off"
},
"8": {
"position": "1",
"type_id": "3",
"different": "off"
}
}
Upvotes: 0
Views: 376
Reputation: 17206
Here is a double loop solution starting from collection
$groups = $collection->toArray();
foreach($groups as $groupIndex => $group) {
foreach($group as $attName => $attValue) {
if ($attValue === "0" && $attName != "position") {
unset($groups[$groupIndex][$attName]);
}
}
}
return json_encode($groups);
Upvotes: 1
Reputation: 43451
Simply apply array_filter
to filter out unwanted content:
function filterEmpty(&$array) {
$array = array_filter(
$array,
function ($key, $value) {
return $key == 'position' || !is_numeric($value) || (int) $value > 0
},
ARRAY_FILTER_USE_BOTH
);
}
array_walk($fooArray, 'filterEmpty');
Upvotes: 1