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

时间:2017-12-29 03:31:43

标签: php arrays filter

我有一个对象数组如下:

Goal forall (d : nat), d + 1 = d -> False.
Proof.
  induction d.
  intros.
  - inversion H.
  - intros H.
    erewrite <- eq_add_S in H; eauto.
Qed.

我希望通过特定键值获取任何数组项。 例如,我想让密钥$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"} ]; 的项目等于day,因此我的数组结果将如下所示:

Tue

我尝试过:

$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"},
    ];

从技术上讲,它按预期工作,但需要编写许多代码。是否还有其他支持此操作的PHP函数?我试过$RESULTS = []; foreach($ARR as $item){ if($item->day == 'Tue'){ $RESULTS[] = $item; } } array_slice,但没有运气。

2 个答案:

答案 0 :(得分:2)

您的实施绝对没有错。我能想到的唯一另一种选择是array_filter

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

你的原始方法很可能比more performant更好,特别是在如此小的阵列中。

另请注意,密钥会随array_filter一起保留,因此您最终会得到索引4和5.您可以使用array_values重新索引数组

$RESULTS = array_values($RESULTS);

答案 1 :(得分:1)

有几种方法可以做到这一点,但是:如果你需要多次做同样的事情,那就需要一个函数:

function pluck(array $ARR, $key, $value) {
    $RESULTS = [];
    foreach ($ARR as $item){
        if ($item->$key == $value) {
            $RESULTS[] = $item;
        }
    }
    return $RESULTS;
}

您可以将其称为:

$RESULTS = pluck($ARR, 'day', 'Tue');
$RESULTS = pluck($ARR, 'isActive', 1);
// etc...

根据需要多次,没有所有重复的代码。也就是说,当然,您可能不希望进行严格的==比较,在这种情况下,您可能会选择更灵活的功能。例如,$value可能是正则表达式,您的函数可以修改为:

        if (preg_match($value, $item->$key) {