Sort array by two specifics values in PHP
The folks have already showed me how to sort an array by a specific value using usort and a fallback function in PHP.
What if this specifc value doesn't exist and we have to use two values? in the example bellow the values [4] and [5]... In other words, I want to do this: order all objects numericaly by the fith value of each object from the highest to the lowest, and addicionally, for those objects that have the fifht value is empty (in the examplem '-'), order them by the fourth value.
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(开发者_如何学JAVA
[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] => -
)
)
// $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');
You just need to change your callback function to return negative, zero or positive numbers depending on the values present (or not) in the two items being compared at any one time; just as you would when comparing a single array index in both items.
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);
In this particular case, the above callback could be whittled down to something like:
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];
}
精彩评论