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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?