# 怎么简化这段代码

• 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
\$arr = [100,100,100,100,120,150,160,183,200];

function find(\$x,\$arr){
\$low = 0;
\$len = count(\$arr);
\$high =\$len-1;
\$result = [];

while (\$low <= \$high){
\$middle = (int)round((\$high + \$low ) / 2);

if(\$x == \$arr[\$middle]){
//result = [middle]
while(\$low<=\$high){
if(\$arr[\$low] === \$x){
array_push(\$result,\$low);
}

\$low++;

}

break;
} else if (\$x>\$arr[\$middle]){
\$low = \$middle+1;
} else {
\$high = \$middle-1;
}
}

if(count(\$result) === 0 ){
\$result =  [\$high,\$low];

if(\$result[0]<=0){
return [0];
}

if(\$result[0] === \$len-1 ){
return [\$len-1];
}
}

return \$result;
}

\$d = find(100,\$arr);

var_dump(\$d);``````

javascript 在线运行可以看下面
http://jsbin.com/lazuwexuji/1...