I am trying to calculate percentiles for users in a database. In order to do this I have a $data
array that I need to sort.
I have a query object that contains User_ID
, Total_User_Orders
, and Total_Orders
. Here's how the code looks so far:
// Loop through the users
foreach($query->result() as $row)
{
(string)$user_id = (string)$row->user_id;
$data[$user_id] = number_format((($row->total_user_orders/$row->total_orders)*100), 5);
}
// Sort the $data array
array_multisort($data);
print_r($data);
What (I believe) that should do is typecast $row->user_id
(an int) as a string. Then, the $data[$user_id]
index should be set as a string - right...?
When I sort the array using array_multisort
it sorts it as though the index was an Integer, rather than a String. This means it loses the index.
The PHP manual for array_multisort()
states, "Associative (string) keys will be maintained, but numeric keys will be re-indexed.". I have also tried using array_multisort($data, SORT_STRING)
, but the same output occurs. However - it does work when I do $data['#'.$user_id]
, but this doesn't quite feel like the right solution to me!
Can anyone help? Thanks in advance!
$data
doesn't look multi-dimensional here, why can't you useasort()
? php.net/manual/en/function.asort.phpnumber_format([...])
etc). But I want to retain the user ID as a key so that I can link up the User ID with their Percentile value later on.asort()
seems to have done the trick just fine!asort()
will sort by the value of the array and maintain the association.