dopnpoh056622 2019-07-19 15:02
浏览 88
已采纳

PHP返回数字在一系列数组之间的键

If I have one php array $date like below:

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
    )

    ...
)

and I also have some random numbers like: 1, 34, 67, 120...

My question is that :

  • when the random number is 1 or 34, then compare it with $date's keys (100, 93, 65), then return empty,
  • when the random number is 67, it will return $date[65], because this number is between 65 and 93.
  • when the random number is 120, it will return $date[100], because this number is between 100 and ∞ (infinite).

If the array $date only has a few elements, I can use for or foreach to compare the keys, but if the array $date has lots of elements, do we have an easy way to do that please?

  • 写回答

1条回答 默认 最新

  • douluchuo0801 2019-07-19 21:59
    关注
    $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;
            }
        }
    }
    

    Returns as expected :

    []
    []
    array:2
      "card" => 1537
      "start_date" => "2019-07-09 00:00:00"
    ]
    array:2
      "card" => 5244
      "start_date" => "2019-05-03 00:00:00"
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化