I want to sort a multidimensional array based on 'distance' value.If distance are equal then i have to compare 'created' date then price and finally alphabetical order.Who can i sort an array based on different key values.
$array = array( 0 => array('title'=>'title1', 'distance'=>200, 'date'=>'2014-16','price'=>12), 1 => array('title'=>'title2', 'distances'=>100, 'date'=>'014-03-15','price'=>17));
array look like this.First priority to distnce then date and so on
I wrote a function for this exact thing,
Checkout My Gist:
https://gist.github.com/chazmead/8829079
<?php
/**
* Sort a 2 dimension array with values in the second dimension
*
* Developer: chazmead89@gmail.com // @RaggaMuffin-4201
*
* Order can be string of a field, which will default to asc
* OR as array(field1,field2...fieldn) each defaulting to asc
* OR as assoc array(field1 => dir[asc|desc], field2 => dir[asc|desc]...fieldn
* => dir[asc|desc])
*
* PHP Sort constants can be used: SORT_ASC | SORT_DESC
*
* @param array $array array to sort - passed by reference
* @param mixed $order
* @return null
*/
function multisort(&$array,$order) {
usort($array, function($a,$b) use ($order) {
$sortMap = array('asc'=>SORT_ASC,'desc'=>SORT_DESC);
$aObj = (object)$a;
$bObj = (object)$b;
if (is_string($order))
$order = array($order);
if (is_object($order))
$order = (array)$order;
$i = 0;
$cOrder = count($order);
foreach($order as $field => $dir) {
if (is_numeric($field)) {
$field = $dir;
$dir = SORT_ASC;
}
// Goto next step when a mis-match is found.
if ($aObj->$field != $bObj->$field)
break;
// All fields match return 0
if (++$i === $cOrder)
return 0;
}
if(!is_numeric($dir)) {
$dir = strtolower($dir);
$dir = $sortMap[$dir];
}
$d = ($dir === SORT_DESC) ? -1 : 1;
$c = ($aObj->$field < $bObj->$field) ? -1 : 1;
return $c*$d;
});
}
This can be used like so:
$array = array( 0 => array('title'=>'title1', 'distance'=>200, 'date'=>'2014-03-16','price'=>12), 1 => array('title'=>'title2', 'distances'=>100, 'date'=>'014-03-15','price'=>17), );
$order = array('distance' => SORT_ASC, 'created' => SORT_ASC, 'title' => SORT_ASC);
multisort($array,$order);