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

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))];
    
    点赞 打赏 评论
  • dongpi3237 2018-10-18 10:26

    You guys where right the previews answer wasn't good enough
    I'v made a work around that works for me, not sure about efficiency

    if (!isset($by_date[$testVal])){
        $by_date[$testVal] = null;
        ksort($by_date);
        $date_key = array_search($price_date,array_keys($by_date));
        $by_date[$testVal] = (array_values($by_date)[$date_key-1]);
    }
    
    $by_date_price =  $by_date[$testVal];
    

    Thank you for the help and comments

    点赞 打赏 评论

相关推荐 更多相似问题