-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkey_sort.php
More file actions
63 lines (54 loc) · 1.23 KB
/
key_sort.php
File metadata and controls
63 lines (54 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
function key_sort(&$array, $attr, $reverse=FALSE, $index_association=TRUE)
{
//sort an array by a particular array key
/*
e.g.
$in_array = array(array("count" => 4,"value" => "apple"), array("count" => 2,"value" => "orange"), array("count" => 6,"value" => "banana"));
key_sort($in_array,"count");
print_r($in_array);
//outputs...
Array
(
[1] => Array
(
[count] => 2
[value] => orange
)
[0] => Array
(
[count] => 4
[value] => apple
)
[2] => Array
(
[count] => 6
[value] => banana
)
)
Optionally $attr can be an array for secondary, third sorting
*/
if($reverse)
$ret_val = 1;
else
$ret_val = -1;
if(!is_array($attr))
$attr = array($attr); //only one attribute to sort on
//(when they pass in an array they can do secondary sorts)
$sort_func = create_function('$a,$b', '
$keys = unserialize(\'' . serialize($attr) . '\');
foreach($keys as $key)
{
if(isset($a[$key]) && isset($b[$key]))
{
if($a[$key] < $b[$key] ) return '.$ret_val.';
elseif($a[$key] > $b[$key] ) return -('.$ret_val.');
}
}
return 0;
');
if(!$index_association)
usort($array, $sort_func);
else
uasort($array, $sort_func);
}