Aleix
Aleix

Reputation: 497

Do a query to an array?

I have this:

$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));

Then I have the variable (which of course is dynamic)

$number= 1.1;

How would I do to get the value 15.5 given that $number is between 1 and 1.5 ?

Upvotes: 0

Views: 61

Answers (2)

biziclop
biziclop

Reputation: 14596

Overcomplicated map-reduce way:

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 );

Upvotes: 1

Will
Will

Reputation: 1619

Iterate through the array.

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

Upvotes: 3

Related Questions