php compare/match range of values
I have an array to which I need to compare data from mysql. Usually I'm doing a straight comparison so I can do an if ($array[$i]===$mysql[$i])
, but I do have one instance where I need to match it against a range of numbers (ex. 18-19, 20-24, etc). I looked into preg_match & preg_grep, but they don't seem to be what I want…
I just need a true/false result from the comparison.
The part of the array I'm trying to match against looks like this:
"age"=>array(
'18-19'=>array('total'=>0,'completed'=>0),
'20-24'=>array('total'=>0,'completed'=>0),
'25-29'=>array('total'=>0,'completed'=>0),
'30-34'=>array('total'=>0,'completed'=>0),
'35-39'=>array('total'=>0,'completed'=>0),
'40-44'=>array('total'=>0,'completed'=>0),
'45-49'=>array('total'=>0,'completed'=>0),
'50-54'=>array('tota开发者_如何学Cl'=>0,'completed'=>0),
'55-59'=>array('total'=>0,'completed'=>0)
),"race"=>array(
"White"=>array('total'=>0,'completed'=>0),
"Black"=>array('total'=>0,'completed'=>0),
"Hispanic"=>array('total'=>0,'completed'=>0),
"Asian"=>array('total'=>0,'completed'=>0),
"Pacific Islander"=>array('total'=>0,'completed'=>0),
"Multiracial"=>array('total'=>0,'completed'=>0),
"Other"=>array('total'=>0,'completed'=>0)
)
Is there a clean way to do this?
Thanks!
list($min,$max) = explode('-', $array[$i]);
if ($mysql[$i] >= $min && $mysql[$i] <= $max) ...
PHP's range() function might be useful:
foreach ($array['age'] as $ageRange => $something) {
list($start, $limit) = explode('-', $ageRange);
foreach (range($start, $limit) as $age) {
// compare
}
}
精彩评论