对数组进行查询?

时间:2012-06-19 16:29:46

标签: php arrays

我有这个:

$array = array(1 => array('min' => 0, 'max' => 0.5, 'value'=>12.5),
2 => array('min' => 0.5, 'max' => 1, 'value'=>13.5),
3 => array('min' => 1, 'max' => 1.5, 'value'=>15.5),
4 => array('min' => 1.5, 'max' => 2, 'value'=>18.5));

然后我有变量(当然是动态的)

$number= 1.1;

如果$number介于11.5之间,我该如何获取值15.5?

2 个答案:

答案 0 :(得分:3)

遍历数组。

function getValue($array, $number){
  foreach($array as $params):
    if($params['min'] < $number and $params['max'] > $number)
      return $params['value'];
  endforeach;
}

答案 1 :(得分:1)

过度复杂的map-reduce方式:

http://codepad.org/s6T86VYf

$array = array(
1 => array('min' => 0, 'max' => 0.5, 'value'=>12.5),
2 => array('min' => 0.5, 'max' => 1, 'value'=>13.5),
3 => array('min' => 1, 'max' => 1.5, 'value'=>15.5),
4 => array('min' => 1.5, 'max' => 2, 'value'=>18.5));

$number= 1.1;

function reduce( $row ){
  global $number;
  return $row['min'] <= $number
      && $row['max'] >= $number;
}

function map( $row ){
  return $row['value'];
}

$reduced = array_filter( $array, 'reduce');

$mapped = array_map('map', $reduced );

print_r( $mapped );