Reputation: 117
I have one problem. I must get 5 images which rates are the biggest. I have table which key = image_id and value = average rating.
Below is print_r of this array
Array ( ['5'] => 5.00 ['4'] => 3.05 ['12'] => 3.00 ['11'] => 4.00 ['21'] => 2.11 ['53'] => 4.44 )
For example
['5'] => 5.00
means that img which id = '5' have rating 5.00
Expected output 2 Arrays ($id and $rating)
Array ( [0] => '5' [1] => '53' [2] => '11' [3] => '4' [4] => '12' )
Array ( [0] => '5.00' [1] => '4.44' [2] => '4.00' [3] => '3.05' [4] => '3.00' )
Can you help me in this?
Upvotes: 1
Views: 100
Reputation:
Use arsort(); and array_slice();
You can also avoid making 2 separate arrays with functions like array_keys(); and array_values();
// Original array
$array = array(
5 => 5.00,
4 => 3.05,
12 => 3.00,
11 => 4.00,
21 => 2.11,
53 => 4.44
);
// Sort array & maintain keys
arsort($array);
// Now get the first 5 elements, keeping the keys
$array = array_slice($array, 0, 5, true);
// IDs
print_r(array_keys($array));
// Ratings
print_r(array_values($array));
Upvotes: 2