Skip to content
Advertisement

Conditional unset from Guzzle response

I’ve seen a few questions and the ones worth referencing

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(...);

enter image description here

If I do

$rooms = json_decode($rooms);

this is what I get

enter image description here

If I do

$rooms = json_decode($rooms, true);

this is what I get

enter image description here


Now sometimes the group exists in the same level as objectId, visibleOn, … and it can assume different values

enter image description here

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 value bananas.

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

enter image description here

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.

Advertisement

Answer

If I am not totally wrong, then this should do the trick for you:

$rooms = json_decode($rooms);
$rooms->results = array_values(array_filter($rooms->results, function($room) {
    return property_exists($room, 'group') && $room->group != "banana";
}));

Here is a verbose and commented version of this one above:

$rooms = json_decode($rooms);

// first lets filter our set of data
$filteredRooms = array_filter($rooms->results, function($room) {
    // add your criteria for a valid room entry
    return
        property_exists($room, 'group') // the property group exists
        && $room->group == "banana";    // and its 'banana'
});

// If you want to keep the index of the entry just remove the next line
$filteredRooms = array_values($filteredRooms);

// overwrite the original results with the filtered set
$rooms->results = $filteredRooms;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement