dongtangze6393 2018-01-10 20:38
浏览 482
已采纳

php查找数组值是否大于变量

Hello a am trying to create a function that will return me a value from the array if the value is bigger the a variable. the array is

[0] => Array ( [payment] => 1 [amount] => 100) 
[1] => Array ( [payment] => 2 [amount] => 300 ) 
[2] => Array ( [payment] => 3 [amount] => 800 )

$variable = 350;

I need to get the payment value if is bigger then 300 amount . what I mean is to get back the value payment = 2. that is bigger then 300 and smaller the 800.

Thanks

  • 写回答

2条回答 默认 最新

  • duanhan3067 2018-01-10 21:09
    关注

    As you said that if you are searching fr 350 it need to return record of amount 300, that means:-

    You are searching for nearest amount first and then get payment value of that corresponding amount

    Do like below:-

    <?php
    
    
    $array = Array(
                '0' => Array ( 'payment' => 1, 'amount' => 100) ,
                '1' => Array ( 'payment' => 2, 'amount' => 300 ) ,
                '2' => Array ( 'payment' => 3, 'amount' => 800 )
            );
    
    function getNearest($search, $arr) {
       $closest = null;
       foreach ($arr as $item) {
          if ($closest === null || abs($search - $closest) > abs($item - $search)) {
             $closest = $item;
          }
       }
       return $closest;
    }
    
    $key = array_search(getNearest(350, array_column($array,'amount')),array_column($array,'amount'));
    
    echo $array[$key]['payment'];
    

    Output:- https://eval.in/933225

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架