I've seen a few questions and the ones worth referencing
- How can i delete object from json file with PHP based on ID
- How do you remove an array element in a foreach loop?
- How to delete object from array inside foreach loop?
- Unset not working in multiple foreach statements (PHP)
The last two from the list are closer to what I'm intending to do.
I've got a variable names $rooms
which is storing data that comes from a particular API using Guzzle
$rooms = Http::post(...);
If I do
$rooms = json_decode($rooms);
this is what I get
If I do
$rooms = json_decode($rooms, true);
this is what I get
Now sometimes the group
exists in the same level as objectId
, visibleOn
, ... and it can assume different values
So, what I intend to do is delete from $rooms
when
group
isn't set (so that specific value, for example, would have to be deleted)group
doesn't have the valuebananas
.
Inspired in the last two questions from the initial list
foreach($rooms as $k1 => $room_list) {
foreach($room_list as $k2 => $room){
if(isset($room['group'])){
if($room['group'] != "bananas"){
unset($rooms[$k1][$k2]);
}
} else {
unset($rooms[$k1][$k2]);
}
}
}
Note that $room['group']
needs to be changed to $room->group
depending on if we're passing true
in the json_decode()
or not.
This is the ouput I get if I dd($rooms);
after that previous block of code
Instead, I'd like to have the same result that I've shown previously in $rooms = json_decode($rooms);
, except that instead of having the 100 records it'd give only the ones that match the two desired conditions.