note 95694 deleted from function.sort by thiago
| From: | thiago@php.net | Date: | Mon, 18 Jan 2010 11:41:26 +0000 |
| Subject: | note 95694 deleted from function.sort by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165067@lists.php.net to get a copy of this message | ||
Note Submitter: noemail at noemail dot com
----
PHP offers dozens of functions for sorting arrays, but unfortunately non of this functions support
sorting by sub-key's value out of the box. It's very useful when you want to sort the
result of a query by an specific column.
Questions/Suggestions?! : send your comments here http://sina.salek.ws/node/1308
Sample :
<?php
$users=array(
array(
'username'=>'Ashkan1',
'age'=>20,
),
array(
'username'=>'Ashkan2',
'age'=>35,
),
array(
'username'=>'Ashkan3',
'age'=>18,
),
);
$users=arraySortTwoDimByValueKey($users,'age','asc');
/*
Result :
array (
array(
'username'=>'Ashkan3',
'age'=>18,
),
array(
'username'=>'Ashkan1',
'age'=>20,
),
array(
'username'=>'Ashkan2',
'age'=>35,
),
)
*/
?>
And the function :
<?php
/**
* Sorting two dimensional array by sub-key's value
* @author sina.salek.ws
* @param $array array
* @param $by string //Sub-key name
* @param $type string //asc,desc
* @return array
*/
function arraySortTwoDimByValueKey($array,$by,$type='asc') {
$sortField=&$by;
$multArray=&$array;
$tmpKey='';
$ResArray=array();
$maIndex=array_keys($multArray);
$maSize=count($multArray)-1;
for($i=0; $i < $maSize ; $i++) {
$minElement=$i;
$tempMin=$multArray[$maIndex[$i]][$sortField];
$tmpKey=$maIndex[$i];
for ($j=$i+1; $j <= $maSize; $j++) {
if ($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
$minElement=$j;
$tmpKey=$maIndex[$j];
$tempMin=$multArray[$maIndex[$j]][$sortField];
}
}
$maIndex[$minElement]=$maIndex[$i];
$maIndex[$i]=$tmpKey;
}
if ($type=='asc') {
for ($j=0;$j<=$maSize;$j++) {
$ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
}
} else {
for ($j=$maSize;$j>=0;$j--) {
$ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
}
}
return $ResArray;
}
?>