I am working with PHP Codeigniter framework and here I have a array value and I want to sort multidimensional array by value descending in Codeigniter. How can I sort multidimensional array by value descending.
I am following this code:
<?php foreach ($data as $my_data) { $fk_post_id= $my_data->fk_post_id; $rating=$get_rating[0]->rating; $storearray[]=['fk_post_id'=>$fk_post_id,'rating'=>$rating]; } ?>
My Output:
Array ( [2] => Array ( [t_fk_post_id] => 67 [rating] => 3 ) [5] => Array ( [t_fk_post_id] => 68 [rating] => 2 ) [4] => Array ( [t_fk_post_id] => 69 [rating] => 10 ) [0] => Array ( [t_fk_post_id] => 70 [rating] => 2 ) [1] => Array ( [t_fk_post_id] => 71 [rating] => 8 ) [3] => Array ( [t_fk_post_id] => 73 [rating] => 10) )
In codeigniter you want to sort multidimensional array by value descending, so you need to first define a array variable, like
I done it using this code, Now follow the example code:
<?php public function myFunction(){ $storearray=array(); // here fetch data using loop foreach ($data as $my_data) { $fk_post_id= $my_data->fk_post_id; $rating=$get_rating[0]->rating; $storearray[]=['fk_post_id'=>$fk_post_id,'rating'=>$rating]; } uasort($storearray, array("HomeController", "sortByOrder")); // HomeController is the controller class name and sortByOrder is the function name which call in the below print_r($storearray); } function sortByOrder($a, $b) { if ($a['rating'] == $b['rating']) { return 0; } return ($a['rating'] < $b['rating']) ? 1 : -1; } ?>
Output:
Array ( [2] => Array ( [t_fk_post_id] => 69 [rating] => 10 ) [5] => Array ( [t_fk_post_id] => 73 [rating] => 10 ) [4] => Array ( [t_fk_post_id] => 71 [rating] => 8 ) [0] => Array ( [t_fk_post_id] => 67 [rating] => 3 ) [1] => Array ( [t_fk_post_id] => 68 [rating] => 2 ) [3] => Array ( [t_fk_post_id] => 70 [rating] => 2) )
Question and answer is powered by AnsPress.io