Find statements in CakePHP produce an array structured as below. I've already ordered my search to produce the result set shown (ordered by combined_score). Now, I'd like to apply a sorting function on the data to sort by "average_votes". See "from this:"/"to this:" below.
I'd really appreciate any suggestions.
From this:
Array
(
[0] => Array
(
[Vehicle] => Array
(
[id] => 52
[user_id] => 101
[name] => Ford
[total_votes] => 5
[average_votes] => 3.8
[combined_score] => 19
)
)
[1] => Array
(
[Vehicle] => Array
(
[id] => 48
[user_id] => 101
[name] => Nissan
[total_votes] => 6
[average_votes] => 5
[combined_score] => 2
)
)
)
To this:
Array
(
[0] => Array
(
[Vehicle] => Array
(
[id] => 48
[user_id] => 101
[name] => Nissan
[total_votes] => 6
[average_votes] => 5
[combined_score] => 2
)
)
[1] => Array
(
[Vehicle] => Array
(
[id] => 52
[user_id] => 101
[name] => Ford
[total_votes] => 5
[average_votes] => 3.8
[combined_score] => 19
)
)
)
Depending on what you're actually trying to achieve you can still do this at the database level in cake, like so:
$this->Vehicle->find('all',array('order' => array('Vehicle.combined_score' => 'asc', 'Vehicle.average_votes' => 'desc')));
Which will first sort by combined score, and then sort by average votes
The second option is to use the cakephp Set class, like so:
$results = Set::sort($results, '{n}.Vehicle.average_votes', 'desc');
In your controller the find function you can add option for sorting.
$this->Vehicle->find('all',array('order' => array('Vehicle.average_votes DESC')));