How to sort array on given key in php?

Sometime we require array in specific order that time we need to sort array in specific order in ascending or descending order as par requirement view.
Using php array key we can sort array in ascending or descending order
Here first argument is pass array data, second is the array key and third one is optional, default showing in ascending order array

function sortbyKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;

ksort($ordered, $sort_flags);
return array_values($ordered);
}

Advertisements

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