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

Advertisements

Sr. Software Engineer

Tagged with: , , ,
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: