note 76872 added to function.uksort
| From: | fgallan at gmail dot com | Date: | Fri, 03 Aug 2007 04:22:16 +0000 |
| Subject: | note 76872 added to function.uksort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129143@lists.php.net to get a copy of this message | ||
muti-array special sort funciton:
<?php
/// mycmp functions ///
function mycmp_asc($a, $b) {
global $_CMP_FORMULA;
static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
if (!$_CMP_FORMULA_VA) {
$_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a',
$_CMP_FORMULA) . ';';
}
if (!$_CMP_FORMULA_VB) {
$_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b',
$_CMP_FORMULA) . ';';
}
eval($_CMP_FORMULA_VA);
eval($_CMP_FORMULA_VB);
if ($va == $vb) return 0;
else return ($va < $vb ? -1 : 1);
}
function mycmp_desc($a, $b) {
global $_CMP_FORMULA;
static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
if (!$_CMP_FORMULA_VA) {
$_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a',
$_CMP_FORMULA) . ';';
}
if (!$_CMP_FORMULA_VB) {
$_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b',
$_CMP_FORMULA) . ';';
}
eval($_CMP_FORMULA_VA);
eval($_CMP_FORMULA_VB);
if ($va == $vb) return 0;
else return ($va > $vb ? -1 : 1);
}
/// run sort ///
$r = array(
array(
'name' => 'name1',
'numbers' => array(1,3,5,7,9),
),
array(
'name' => 'name2',
'numbers' => array(5,6,7,8,9),
),
array(
'name' => 'name3',
'numbers' => array(1,2,3,4,5),
),
);
global $_CMP_FORMULA;
$_CMP_FORMULA = 'array_sum({}["numbers"])';
usort($r, "mycmp_desc");
echo '<pre>'; print_r($r); echo '</pre>';
?>
print:
Array
(
[0] => Array
(
[name] => name2
[numbers] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
[4] => 9
)
)
[1] => Array
(
[name] => name1
[numbers] => Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 7
[4] => 9
)
)
[2] => Array
(
[name] => name3
[numbers] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
)
)
----
Server IP: 69.147.83.197
Probable Submitter: 222.66.106.194
----
Manual Page -- http://www.php.net/manual/en/function.uksort.php
Edit -- https://master.php.net/note/edit/76872
Del: integrated -- https://master.php.net/note/delete/76872/integrated
Del: useless -- https://master.php.net/note/delete/76872/useless
Del: bad code -- https://master.php.net/note/delete/76872/bad+code
Del: spam -- https://master.php.net/note/delete/76872/spam
Del: non-english -- https://master.php.net/note/delete/76872/non-english
Del: in docs -- https://master.php.net/note/delete/76872/in+docs
Del: other reasons-- https://master.php.net/note/delete/76872
Reject -- https://master.php.net/note/reject/76872
Search -- https://master.php.net/manage/user-notes.php