Guzzle 响应中的条件取消设置

Conditional unset from Guzzle response

我看到了一些问题和值得参考的问题

列表中的最后两个更接近我打算做的。


我有一个变量名称 $rooms,它使用 Guzzle

存储来自特定 API 的数据
$rooms = Http::post(...);

如果我这样做

$rooms = json_decode($rooms);

这就是我得到的

如果我这样做

$rooms = json_decode($rooms, true);

这就是我得到的


现在有时 groupobjectIdvisibleOn 处于同一级别,...并且它可以采用不同的值

所以,我打算做的是在

时从 $rooms 中删除

灵感来自初始列表的最后两个问题

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]);
        }
    }
}

请注意,$room['group'] 需要更改为 $room->group,具体取决于我们是否在 json_decode() 中传递 true

这是我在上一个代码块

之后dd($rooms);得到的输出

相反,我想要得到与我之前在 $rooms = json_decode($rooms); 中显示的结果相同的结果,只是它不会提供 100 条记录,而是只给出符合两个所需条件的记录.

如果我没有完全错的话,那么这应该对你有用:

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

这是上面这个版本的详细注释版本:

$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;