人们已经向我展示了如何使用PHP中的usort和回退函数按特定值对数组进行排序。
如果此特定值不存在并且我们必须使用两个值,该怎么办?在示例中,值[4]和[5] ...换句话说,我想这样做:按照每个对象的fith值从最高到最低对所有对象进行数值排序而且,对于那些具有fifht值为空的对象(在examplem' - '中),按第四个值排序。
Array(
[0] => Array(
[0] => links-patrocinados
[1] => adwords
[2] => 0,5
[3] => R$92,34
[4] => 823000
[5] => 49500
)
[1] => Array(
[0] => adwords
[1] => google adwords como funciona
[2] => 0,38
[3] => R$0,20
[4] => 480
[5] => 480
)
[2] => Array(
[0] => links-patrocinados
[1] => adword
[2] => 0,39
[3] => R$58,77
[4] => 49500
[5] => 2900
)
[3] => Array(
[0] => agencia
[1] => agencias viagens espanholas
[2] => -
[3] => R$0,20
[4] => 58
[5] => -
)
[4] => Array(
[0] => agencia
[1] => era agencia imobiliaria
[2] => -
[3] => R$0,20
[4] => 73
[5] => -
)
)
答案 0 :(得分:5)
// $myArray = your array of associative arrays, above
function compare($x, $y)
{
if ( $x[5] == $y[5] ) {
return 0;
}
else if ( $x[5] < $y[5] ) {
return -1;
}
else {
return 1;
}
}
usort($myArray, 'compare');
答案 1 :(得分:2)
您只需更改回调函数即可返回负数,零或正数,具体取决于任何时候两个项目中存在(或不存在)的值;就像比较两个项目中的单个数组索引一样。
function callback($a, $b) {
// Both have [5] so sort by that
if ($a[5] !== '-' && $b[5] !== '-')
return $b[5] - $a[5];
// Neither have [5] so sort by [4]
if ($a[5] === '-' && $b[5] === '-')
return $b[4] - $a[4];
// One has a [5] value
if ($a[5] === '-')
return 1;
else
return -1;
}
uasort($array, 'callback');
print_r($array);
在这种特殊情况下,上述回调可以缩小为:
function callback($a, $b) {
// Neither have [5] so sort by [4]
if ($a[5] === '-' && $b[5] === '-')
return $b[4] - $a[4];
// One, or both, has a [5] value
return $b[5] - $a[5];
}