note 77537 added to function.sort
| From: | davidwhthomas at gm at 1l dot c0m | Date: | Mon, 03 Sep 2007 01:02:16 +0000 |
| Subject: | note 77537 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-130110@lists.php.net to get a copy of this message | ||
Here's a variation on the above function to sort arrays with more than one key by an arbitrary
key's value.
This function allows sorting of an array of objects too
<?php
/**
* Sorts an array of objects by the value of one of the object properties or array keys
*
* @param array $array
* @param key value $id
* @param boolean $sort_ascending
* @param boolean $is_object_array
* @return array
*/
function vsort($array, $id="id", $sort_ascending=true, $is_object_array = false) {
$temp_array = array();
while(count($array)>0) {
$lowest_id = 0;
$index=0;
if($is_object_array){
foreach ($array as $item) {
if (isset($item->$id)) {
if ($array[$lowest_id]->$id) {
if ($item->$id<$array[$lowest_id]->$id) {
$lowest_id = $index;
}
}
}
$index++;
}
}else{
foreach ($array as $item) {
if (isset($item[$id])) {
if ($array[$lowest_id][$id]) {
if ($item[$id]<$array[$lowest_id][$id]) {
$lowest_id = $index;
}
}
}
$index++;
}
}
$temp_array[] = $array[$lowest_id];
$array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array,
$lowest_id+1));
}
if ($sort_ascending) {
return $temp_array;
} else {
return array_reverse($temp_array);
}
}
?>
Sample Usage:
<?php
$nodes = vsort($nodes,'term_data_weight', false, true);
print '<pre>'.print_r($nodes,1).'</pre>';
?>
----
Server IP: 203.89.181.186
Probable Submitter: 202.78.240.7
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- https://master.php.net/note/edit/77537
Del: integrated -- https://master.php.net/note/delete/77537/integrated
Del: useless -- https://master.php.net/note/delete/77537/useless
Del: bad code -- https://master.php.net/note/delete/77537/bad+code
Del: spam -- https://master.php.net/note/delete/77537/spam
Del: non-english -- https://master.php.net/note/delete/77537/non-english
Del: in docs -- https://master.php.net/note/delete/77537/in+docs
Del: other reasons-- https://master.php.net/note/delete/77537
Reject -- https://master.php.net/note/reject/77537
Search -- https://master.php.net/manage/user-notes.php