# 怎么简化这段代码

• 190

\$amount = 100; //110,90,200
\$arr = [98,100,100,120,150,160,183];

\$amount = 100;    返回 [1,2];
\$amount = 110;    返回 [2,3];
\$amount = 90;     返回 [0];
\$amount = 200;    返回 [6];

\$key   = [];    //下标值的数组
\$count = count(\$arr) - 1;

foreach(\$arr as \$k => \$v){
if(\$amount == \$v){
\$key[] = \$k;
}
}
if(empty(\$key)){
foreach(\$arr as \$k => \$v){
if(\$amount < \$arr[0]){
\$key[] = '';
break;
}
}
}
if(empty(\$key)){
foreach(\$arr as \$k => \$v){
if(\$amount > \$arr[\$count]){
\$key[] = \$count;
break;
}
}
}
if(empty(\$key)){
foreach(\$arr as \$k => \$v){
if(\$amount >= \$arr[\$k] && \$amount < \$arr[\$k + 1]){
\$key[] = \$k;
\$key[] = \$k + 1;
}
}
}
var_dump(\$key);

##### 8个回答

<?php

\$amount = 110; //110,90,200
\$arr = [98,100,100,120,150,160,183];
\$key   = [];
\$arr_length = count(\$arr);
for (\$i=0; \$i<\$arr_length; \$i++) {
if(\$amount == \$arr[\$i] || (empty(\$key) && \$amount > \$arr[\$i] && \$i == \$arr_length - 1)){
\$key[]=\$i;
}
if(empty(\$key) && \$amount < \$arr[\$i]) {
\$i-1>=0 ? array_push(\$key, \$i-1, \$i) : \$key[]=\$i;
break;
}
}

var_dump(\$key);

?>