我有这种阵列:
$arrVar = array(
0 => array(
'val'=> 9
),
1 => array(
'val'=> 12,
),
2 => array(
'val'=> 4
),
);
如何根据变量$ myVar创建一个返回数组索引的函数? 例如:
如果$myVar = 4
该函数将返回$arrVar['2']
如果$myVar = 8
该函数将返回$arrVar['2']
如果$myVar = 10
该函数将返回$arrVar['0']
这是我的数组
$arrVar = array(
0 => array(
'qty'=>9,
'disc'=> 0.15
),
1 => array(
'qty'=>12,
'disc'=> 0.20
),
2 => array(
'qty'=>4,
'disc'=> 0.10
),
);
答案 0 :(得分:1)
使用以下php函数计算折扣百分比:
function searchArr($needle) {
global $arrVar;
$arr=array();
foreach($arrVar as $key => $value) {
$vals = array_values($value);
$arr[$vals[0]] = $vals[1];
}
ksort($arr);
$prev=0;
foreach($arr as $key => $value) {
if ($needle < $key)
return 100 * ($prev==0 ? $value : $prev);
$prev = $value;
}
return 100 * $prev;
}
<强>测试强>
echo "Discount: " . searchArr(4) . "%\n";
echo "Discount: " . searchArr(8) . "%\n";
echo "Discount: " . searchArr(10) . "%\n";
echo "Discount: " . searchArr(12) . "%\n";
<强>输出:强>
Discount: 10%
Discount: 10%
Discount: 15%
Discount: 20%
请参阅此处运行的代码:http://ideone.com/zLDen