从两个值之间的多维数组中获取数组

时间:2018-08-12 01:58:25

标签: php

我有一个像这样的数组:

Array
(
    [0] => Array
        (
            [date] => 1523752578
            [weight1] => 1890
            [weight2] => 1760
        )

    [1] => Array
        (
            [date] => 1523756192
            [weight1] => 1890
            [weight2] => 1760
        )

    [2] => Array
        (
            [date] => 1523759807
            [weight1] => 1890
            [weight2] => 1760
        )

    [3] => Array
        (
            [date] => 1523763423
            [weight1] => 1890
            [weight2] => 1760
        )
)

如何从两个[日期]值之间的数组中获取一个数组?

示例,第一个值为1523756192,第二个值为1523763423,该值应返回包含[1][2][3]的数组,但是而不是[0],并且该数组仍应包含[weight1][weight2]

“ to”和“ from”值将来自两个输入,其中用户选择两个日期。然后,我将从两个日期之间的父数组中选择所有子数组。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找array_filter

function filterbydate($arr, $lowdate, $highdate) {
    return array_filter($arr, function($val) use ($lowdate, $highdate) {
                 return $val['date'] >= $lowdate && $val['date'] <= $highdate;
               });
}

// your data
$arr = [['date' => 1523752578,
         'weight1' => 1890,
         'weight2' => 1760],
        ['date' => 1523756192,
         'weight1' => 1890,
         'weight2' => 1760],
        ['date' => 1523759807,
         'weight1' => 1890,
         'weight2' => 1760],
        ['date' => 1523763423,
        'weight1' => 1890,
        'weight2' => 1760]];

var_dump(filterbydate($arr, 1523756192, 1523763423));

请注意,这将保留索引值,因此结果将具有1、2和3的索引。如果希望对它们重新编号,则可以在结果数组上使用array_values-因此,将filterbydate内部替换为:

    return array_values(
            array_filter($arr, function($val) use ($lowdate, $highdate) {
                 return $val['date'] >= $lowdate && $val['date'] <= $highdate;
               }));