lundi 12 janvier 2015

PHP getting count for values that falls within expected ranges

I have a list containing a bunch of values from 1-400. I am trying to divide the data into ranges like [1-50], [51-100], .. , [351-400] and get the count for the values that falls within the range given . I basically have the code working. So, my question would be is there a better way to do this or what would be a good practise for this?



$temp = array(); //temp array to store the values from mysql
$final_array = array //final array to store the counts from the range initialized to 0
(
"0" => 0,
"1-50" => 0,
"51-100" => 0,
"101-150" => 0,
"151-200" => 0,
"201-250" => 0,
"251-300" => 0,
"301-350" => 0,
"351-400" => 0
);

$sql = "SELECT count(*) AS total FROM user GROUP BY user_id";

$statement = $DB_->link->prepare ( $sql );
$statement->execute ();

if ($result = $statement->get_result ())
{
while ( $row = $result ->fetch_assoc() )
{
$temp [] = $row;
}
}
else
{
die(mysql_error());
}

foreach ($temp as $child)
{
if( $child['total'] >= 351 && $child['total'] <= 400)
{
$final['351-400']++;
}
elseif( $child['total'] >= 301 && $child['total'] <= 350)
{
$final['301-350']++;
}
...
elseif( $child['total'] >= 1 && $child['total'] <= 50)
{
$final['1-50']++;
}
}


Desired results



Array
(
[0] => 0
[1-50] => 1
[51-100] => 0
[101-150] => 0
[151-200] => 1
[201-250] => 0
[251-300] => 4
[301-350] => 5
[351-400] => 18
)

Aucun commentaire:

Enregistrer un commentaire