如何解决Guzzle 响应的条件取消设置
我看到了一些问题和值得参考的问题
- 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)
列表中的最后两个更接近我打算做的事情。
我有一个变量名 $rooms
,它使用 Guzzle 存储来自特定 API 的数据
$rooms = Http::post(...);
如果我这样做
$rooms = json_decode($rooms);
这是我得到的
如果我这样做
$rooms = json_decode($rooms,true);
这是我得到的
现在有时 group
与 objectId
、visibleOn
、... 存在于同一级别,并且它可以采用不同的值
所以,我打算做的是从 $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);
,这是我得到的输出
相反,我希望得到与之前在 $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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。