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

时间:2018-01-10 20:38:18

标签: php arrays

你好我正在尝试创建一个函数,如果值大于变量,它将从数组中返回一个值。  数组是

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

$ variable = 350;

如果金额超过300金额,我需要获得付款金额。 我的意思是取回价值支付= 2.大于300而小于800.

谢谢

2 个答案:

答案 0 :(得分:1)

如你所说,如果你正在搜索fr 350,它需要返回金额300的记录,这意味着: -

您正在搜索最近的金额,然后获得相应金额的payment

如下所示: -

<?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'];

输出: - https://eval.in/933225

答案 1 :(得分:0)

好吧......弗兰肯斯坦来了! :)

&#13;
&#13;
<?php
/*
	if Lazarus is dead .. i bring him alive,
	if Lazarus is wrong .. i'll fix it..
	and any Lazarus doesn't exist i'll invent one
                                                 .. with php,

	mi me mi !

*/
function myArray($ar){
	function searchx($n){
		if(($n['amount']>$GLOBALS['val_search_min'])and($n['amount']<$GLOBALS['val_search_max'])) return($n);
		//mofify the condition how you like ... i put    x>min and x<max     inside here!

	}
	$values=array_map("searchx", $ar);

	return array_filter($values);
}



$arrayx=Array(
	Array ('payment' => 1, 'amount' => 100),
	Array ('payment' => 2,'amount' => 300 ),
	Array ('payment' => 3,'amount' => 800 ),
	Array ('payment' => 2,'amount' => 200 ),
	Array ('payment' => 3,'amount' => 500 ),
	Array ('payment' => 2,'amount' => 400 ),
	Array ('payment' => 3,'amount' => 700 )
);

//a kind of interval:
$val_search_min=300;
$val_search_max=800;

$igotthese=myArray($arrayx);

echo('the result of my stupid function is:<pre>');
var_dump($igotthese);
echo('</pre>');
?>
&#13;
&#13;
&#13;

我到达的结果..推送运行代码段

&#13;
&#13;
the result of my stupid function is:<pre>array(3) {
  [4]=>
  array(2) {
    ["payment"]=>
    int(3)
    ["amount"]=>
    int(500)
  }
  [5]=>
  array(2) {
    ["payment"]=>
    int(2)
    ["amount"]=>
    int(400)
  }
  [6]=>
  array(2) {
    ["payment"]=>
    int(3)
    ["amount"]=>
    int(700)
  }
}
</pre>
&#13;
&#13;
&#13;