我的情况是我的物品价格在公斤范围内,比如
price in range 0.01-0.04 is 5
price in range 0.05-0.09 is 30
price in range 0.1-0.15 is 50
这是我想要的数组样本
$prices = array("0.01-0.04"=>5,"0.05-0.09"=>30);
现在我想创建一个数组,以便在用户输入0.02 it should return price in range 0.01-0.04
时为5,类似用户input 0.07 so it should return 30
。
如何在PHP中创建数组以通过一系列索引访问数组?
答案 0 :(得分:2)
试用此代码
<?php
$price = array(
array(
'min_range' => 0.1,
'max_range' => 0.4,
'price' => 5
),
array(
'min_range' => 0.5,
'max_range' => 0.9,
'price' => 30
),
array(
'min_range' => 1.0,
'max_range' => 1.5,
'price' => 50
),
);
$input = 0.7;
foreach( $price as $p){
if($input>=$p['min_range'] && $input<=$p['max_range']){
echo $p['price'];
break;
}
}
?>
答案 1 :(得分:2)
将$ no变量设置为您要查找范围的数字
<?php
$no = 0.05;
$ranges = array
(
array(0.01,0.04,5),
array(0.05,0.09,30),
array(0.1,0.15,50)
);
$foundFlag=false;
foreach ($ranges as $range) {
if($no>=$range[0] && $no<=$range[1])
{
$foundFlag=true;
echo "$range[2]";
}
}
if($foundFlag==false)
{
echo "range not found";
}
?>
答案 2 :(得分:0)
你也可以这样尝试,
<?php
$input = $_POST['userInput'];
$count = 0;
$arr =Array();
$arr[0]=0.01;
$arr[1]=0.04;
$arr[2]=0.05;
$arr[3]=0.09;
$arr[4]=0.1;
$arr[5]=0.15;
$price =Array();
$price[0] =5;
$price[2] =30;
$price[4] =50;
while(count($arr)>$count)
if($arr[$count] != null && $arr[$count+1] != null)
{
if($input >$arr[$count] && $input <$arr[$count+1])
{
echo "price is $price[$count]";
}
}
$count = $count +2;
}
?>
答案 3 :(得分:0)