Reputation: 195
i have these array and what i need to do is to get the separate each array check the [total] and then get the bigest 5 numbers. ive been trying but my head is about to explode, please help!!
Array (
[0] => Array ( [id] => 50 [faceid] => 1508653983 [fname] => Mario [lname] => Zelaya [email] => Email [handicap] => Handicap [province] => Province [country] => Country [gender] => male [hand] => [shot1] => Shot #1 [shot2] => Shot #2 [shot3] => Shot #3 [shot4] => Shot #4 [shot5] => Shot #5 [news] => 1 [total] => 0 )
[1] => Array ( [id] => 49 [faceid] => 1665349411 [fname] => Yair [lname] => Villar [email] => [email protected] [handicap] => lefthanded [province] => Buenos Aires [country] => Argentina [gender] => male [hand] => RH [shot1] => 200 [shot2] => 98 [shot3] => 98 [shot4] => 98 [shot5] => 98 [news] => 1 [total] => 592 )
[2] => Array ( [id] => 48 [faceid] => 1665349411 [fname] => Yair [lname] => Villar [email] => [email protected] [handicap] => lefthanded [province] => Buenos Aires [country] => Argentina [gender] => male [hand] => RH [shot1] => 500 [shot2] => 250 [shot3] => 80 [shot4] => 30 [shot5] => 20 [news] => 1 [total] => 88000 )
)
how can i do these with php. please help!!
Upvotes: 0
Views: 104
Reputation: 917
function getTop5(array $data, $high2low = true)
{
$total = array();
foreach ($data as $val)
$total[$val["id"]] = $val["total"];
asort($total);
return $high2low ? array_reverse($total) : $total;
}
$data = array(
array("id" => 1, "total" => 25),
array("id" => 2, "total" => 32),
array("id" => 3, "total" => 21),
array("id" => 4, "total" => 28)
);
print_r(getTop5($data));
Upvotes: 1
Reputation: 843
Try using php's usort function to sort your array:
function cmp($a, $b)
{
if ($a['total'] == $b['total'])
return 0;
return ($a['total'] > $b['total']) ? -1 : 1;
}
usort($yourarray, "cmp");
if (count($yourarray) > 5)
$sortedArray = array_slice($yourarray, 0, 5);
else
$sortedArray = $yourarray;
You will end up with an array with the 5 elements with the highest score. If there are less than 5 elements in your input array, you end up with as many elements as there are in your input array.
Upvotes: 2