我经历了所有类似的问题,但找不到答案......所以这就是。
我当前的数组,简化:
[order] => Array ( [0] => Array ( [strSupplier] => XYZ (varying other fields) ) [1] => Array ( [strSupplier] => XYZ (varying other fields) ) [2] => Array ( [strSupplier] => YYZ (varying other fields) ) )
代码:
function custom_sort2($a,$b) { return $a['strSupplier']>$b['strSupplier']; } // Sort the multidimensional array usort($tempOrderArray, "custom_sort2");
目前,我只对供应商进行排序,但是,我需要确保密钥是第二个排序标准,我不确定它是不是。
有没有办法可以保证首先按strSupplier排序,然后键?如果将其内置到uasort或usort函数中,我道歉 - 我没有看到它。
答案 0 :(得分:1)
你的阵列想这样:
[order] => Array
(
[0] => Array
(
[key] => 0,
[strSupplier] => 'XYZ',
//(varying other fields)
)
[1] => Array
(
[key] = 1,
[strSupplier] => 'XYZ',
//(varying other fields)
)
[2] => Array
(
[key] = 2,
[strSupplier] => 'YYZ',
//(varying other fields)
)
)
然后,排序时:
function custom_sort2($a, $b) {
$cmp = $cmpstr = strcmp($a['strSupplier'], $b['strSupplier']); //Compare the string
$cmpkey = ($a['key'] == $b['key'] ? 0 : ($a['key'] > $b['key'] ? 1 : -1)); //Compare the key
if ($cmpkey == 1)
$cmp = ($cmpstr >= 0) ? 1 : 0;
return $cmp; //If we are moving the element forward, then we need to check the key.
}
// Sort the multidimensional array
uasort($array, "custom_sort2");
答案 1 :(得分:0)
您可以先尝试使用ksort,然后按供应商排序。