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 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计