I have the following example data in PHP:
[{"id": 2088996538},{},{"id": 2077495673}]
How can I end up with
[{"id": 2088996538},{"id": 2077495673}]
I've tried several things, like
unset($activities[1]);
but then I end up with
{"0":{"id":2088996538},"2":{"id":2077495673}}
It looks like something soo simple, but can't figuring it out.
The ultimate goal is to clean up some strava api output, deleting everything I don't use.
Edit:
$activities = json_decode('[{"id": 2088996538},{},{"id": 2077495673}]');
unset($activities[1]);
$activities = array_values($activities);
echo json_encode($activities);
this actually works, how could I've missed it. Gonna try it out with the larger data set. Thanks!
You can filter out the empty objects.
$data = array_values(array_filter($data, function($item) {
return (bool) (array) $item;
}));
array_values is necessary to prevent the {"0":{"id":2088996538},"2":{"id":2077495673}} form you were getting, because it reindexes the array.
The intermediate cast to array in the callback is necessary because any object evaluates to true whether it's empty or not, but an empty array will evaluate to false. If you decode to arrays instead of objects by setting the second parameter of json_decode to true, that cast isn't necessary.
Not directly related to the original question, but here's my suggestion for another way to do this starting with the data from the API:
$activities = json_decode($json, true);
$set_keys = array_flip(["start_latlng", "id", "start_date","name"]);
foreach ($activities as $activity) {
if (!is_null($activity['start_latlng'])) {
$result[] = array_intersect_key($activity, $set_keys);
}
}
echo json_encode($result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With