首页 > 解决方案 > 从两个值之间的多维数组中获取一个数组

问题描述

我有一个这样的数组:

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
        )
)

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

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

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

标签: php

解决方案


I think you are looking for 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));

Please note, this retains index values, so the results will have indices of 1, 2, and 3. If you want them renumbered, you can use array_values on the resultant array - so replace the filterbydate internals with:

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

推荐阅读