dsajkdadsa14222 2018-10-17 12:43
浏览 190
已采纳

PHP获取键值或最大值

I'v got this array:

$by_date = array(
    "2018-10-05"=>54,
    "2018-10-07"=>20,
    "2018-10-08"=>31,
    "2018-10-12"=>52
    );

I want to get value by date, but if the date doesn't exist get the lowest date value

for example:

if the date is "2018-10-07" I'll get 20

and if the date is "2018-10-10" I'll get 31

that can go to bigger differences between the date and the last key in the array

For example, if the date is "2019-01-25" I'll get 52 because "2018-10-12" is the last key in the array.

Thanks for the help :)

  • 写回答

2条回答 默认 最新

  • doumu9799 2018-10-17 12:50
    关注

    You can do it with a simple if condition that uses isset() to check for your input as a key on the array. If the condition is met, you return the matched value, otherwise, use max() and array_keys() to return the value with the highest key.

    $by_date = array(
        "2018-10-05"=>54,
        "2018-10-07"=>20,
        "2018-10-08"=>31,
        "2018-10-12"=>52
        );
    
    $testVal = '2018-10-12'
    
    if (isset($by_date[$testVal]))
        return $by_date[$testVal];
    else 
        return $by_date[max(array_keys($by_date))];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料