Guzzle 响应的条件取消设置

问题描述

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

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


我有一个变量名 $rooms,它使用 Guzzle 存储来自特定 API 的数据

$rooms = Http::post(...);

enter image description here

如果我这样做

$rooms = json_decode($rooms);

这是我得到的

enter image description here

如果我这样做

$rooms = json_decode($rooms,true);

这是我得到的

enter image description here


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

enter image description here

所以,我打算做的是从 $rooms 删除

  • group 未设置(例如,必须删除特定值)

  • group 没有值 bananas

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

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,具体取决于我们是否在 true 中传递 json_decode()

如果我在前一个代码块之后dd($rooms);,这是我得到的输出

enter image description here

相反,我希望得到与之前在 $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;