PHP返回数字在数组范围之间的键

时间:2019-07-19 15:02:10

标签: php arrays compare

如果我有一个如下所示的php数组$date

Array
(
    [100] => Array
    (
        [card] => 5244
        [start_date] => 2019-05-03 00:00:00
    )
    [93] => Array
    (
        [card] => 9526
        [start_date] => 2019-05-20 00:00:00
    )
    [65] => Array
    (
        [card] => 1537
        [start_date] => 2019-07-09 00:00:00
    )

    ...
)

我也有一些随机数,例如:1, 34, 67, 120...

我的问题是:

  • 当随机数为1或34时,将其与$date的键(100、93、65)进行比较,然后返回空值,
  • 当随机数为67时,它将返回$date[65],因为该数字介于65和93之间。
  • 当随机数为120时,它将返回$date[100],因为此数在100到∞(无限)之间。

如果数组$date仅包含几个元素,我可以使用 for foreach 来比较键,但是如果数组{{1} }有很多元素,请问有一种简便的方法吗?

1 个答案:

答案 0 :(得分:0)

$dates = [
    100 => [
        'card' => 5244,
        'start_date' => '2019-05-03 00:00:00'
    ],
    93 => [
        'card' => 9526,
        'start_date' => '2019-05-20 00:00:00'
    ],
    65 => [
        'card' => 1537,
        'start_date' => '2019-07-09 00:00:00'
    ]
];
$randoms = [1, 34, 67, 120];
foreach ($randoms as $random) {
    $matchDate = $this->matchDates($dates, $random);
    var_dump($matchDate);
}

/**
 * @param array $dates
 * @param $random
 * @return array
 */
protected function matchDates(array $dates, $random): array
{
    $minKey = min(array_keys($dates));
    $maxKey = max(array_keys($dates));

    if ($random < $minKey) {
        return [];
    }

    if ($random > $maxKey) {
        return $dates[$maxKey];
    }

    foreach ($dates as $key => $date) {
        if ($random >= $key) {
            return $date;
        }
    }
}

按预期返回:

[]
[]
array:2
  "card" => 1537
  "start_date" => "2019-07-09 00:00:00"
]
array:2
  "card" => 5244
  "start_date" => "2019-05-03 00:00:00"
]