# 怎么简化这段代码

\$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 个回答
``````
//在假设已经做过去重和排序的时候：

\$arr = [];
\$r   = rand(5,10);

for(\$i=0;\$i<\$r;\$i++){
\$arr[] = rand(1,10) + (\$i>1?\$arr[\$i-1]:0);
}
\$m = rand(0,100);

// main function
\$l = \$c = \$r = 0;
foreach( \$arr as \$k => \$v ){
if(\$v === \$m){
\$c = \$k;
}else if(\$v<\$m){
\$l = \$k;
\$r = \$k+1;
}
}
\$key = (\$c||!\$l ) ? [\$c] : ( \$r===count(\$arr) ? [\$l] : [\$l,\$r] );

// test
var_dump( \$arr );
var_dump( \$m );
var_dump( \$l );
var_dump( \$c );
var_dump( \$r );
var_dump( \$key );

``````