How sort the array on base of array key:PHP

Hello friends!
Hope you doing well :)
If you want to sort the array on base of array key then just follow my code given below:

<?php
$myarray = array(
array("name"=>"Bob","price"=>8,"colour"=>"red"),
array("name"=>"Greg","price"=>12,"colour"=>"blue"),
array("name"=>"Andy","price"=>5,"colour"=>"purple"));
$sortArray = array();
foreach($myarray as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}
$orderby = "price"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_ASC,$myarray);
echo '<pre>';
print_r($people);
?>

Output :

Array (
[0] => Array ( [name] => Andy [price] => 5 [colour] => purple )
[1] => Array ( [name] => Bob [price] => 8 [colour] => red )
[2] => Array ( [name] => Greg [price] => 12 [colour] => blue )
)

Enjoy Code! | Raghunath Blog

Leave a Reply

Your email address will not be published. Required fields are marked *