gpt4 book ai didi

php - 如何在php中通过键值从数组对象获取数组项

转载 作者:行者123 更新时间:2023-12-02 14:45:48 26 4
gpt4 key购买 nike

我有一个对象数组,如下所示:

$ARR =[
{"id":55,"timetable_id":1,"day":"Sat","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":54,"timetable_id":1,"day":"Fri","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":53,"timetable_id":1,"day":"Thu","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":52,"timetable_id":1,"day":"Wed","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":51,"timetable_id":1,"day":"Tue","checkin":"14:00:00","checkout":"17:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":50,"timetable_id":1,"day":"Tue","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":49,"timetable_id":1,"day":"Mon","checkin":"14:00:00","checkout":"16:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":48,"timetable_id":1,"day":"Mon","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"}
];

我想通过特定的键值获取任何数组项。例如,我想获取等于 Tue 的键 day 的项目,因此我的数组结果将如下所示:

$RESULTS=[
{"id":51,"timetable_id":1,"day":"Tue","checkin":"14:00:00","checkout":"17:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
{"id":50,"timetable_id":1,"day":"Tue","checkin":"07:00:00","checkout":"11:00:00","isActive":1,"created_at":"2017-12-28 19:40:23","updated_at":"2017-12-28 19:40:23"},
];

我尝试过的:

$RESULTS = [];
foreach($ARR as $item){
if($item->day == 'Tue'){
$RESULTS[] = $item;
}
}

从技术上讲,它按预期工作,但需要编写很多行代码。还有其他PHP函数支持这个操作吗?我尝试了 array_slice 和 array_search 但没有运气。

最佳答案

您的实现绝对没有任何问题。我能想到的唯一其他选择是 array_filter

$RESULTS = array_filter($ARR, function($item) {
return $item->day === 'Tue';
});

您最初的方法很可能是 more performant但比这个更重要,尤其是在这么小的数组中。

另请注意,键是用 array_filter 保留的,因此最终会得到索引 4 和 5。您可以使用 array_values 重新索引数组

$RESULTS = array_values($RESULTS);

关于php - 如何在php中通过键值从数组对象获取数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48017060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com