Table of Contents

quick_sort

WattmonOS 3.14+

Sort an array using the quick sort algorithm

Library

/lib/uphp/array.inc

Description

$array quick_sort ( array $array_to_sort , int $method [, string $callback ] )

Sort an array by key, value or using a callback function

Parameters

$array_to_sort: Array to be sorted

$method: One of the following methods:

TYPEVALUEDESCRIPTION
SORT_KEY 0 Sort an array by the key
SORT_VALUE 1 Sort an array by the value
SORT_FUNC 2 Sort an array using a callback function * only in OS4+

$callback: optional string containing function name for callback of the method is SORT_FUNC. The function needs to have 2 parameters, which will be the array elements. These need to be compared and if the first array is less than the second array, the function should return 1, otherwise it should return 0. See the example below.

Return Values

array containing the sorted values

Example

Sort an array using a callback to look at the array elements. The array contains a sub-array for each element with the keys 'order' and 'name'.

<pre><? 
 
include("/lib/uphp/array.inc");
 
$unsorted = array();
for ($i=0;$i<10;$i++) {
    $arr=array();
    $arr['order']=rand(0,100);
    $arr['name']='item'.$i;
    $unsorted[]=$arr;
}
 
function compare($a1,$a2) {
    if ($a1['order'] < $a2['order']) return 1;
    return 0;
}
 
$sorted = quick_sort($unsorted, SORT_FUNC,'compare');
 
print_r($sorted); // spew out the sorted array
 
?></pre>