Mantener la clave de índice del array al ordenar un array multidimensional con PHP
array(10) {
[1019]=> array(3) { ["quantity"]=> int(0) ["revenue"]=> int(0) ["seller"]=> string(5) "Lenny" }
[1018]=> array(3) { ["quantity"]=> int(5) ["revenue"]=> int(121) ["seller"]=> string(5) "Lenny" }
[1017]=> array(3) { ["quantity"]=> int(2) ["revenue"]=> int(400) ["seller"]=> string(6) "Anette" }
[1016]=> array(3) { ["quantity"]=> int(25) ["revenue"]=> int(200) ["seller"]=> string(6) "Samuel" }
[1015]=> array(3) { ["quantity"]=> int(1) ["revenue"]=> int(300) ["seller"]=> string(6) "Samuel" }
[1014]=> array(3) { ["quantity"]=> string(2) "41" ["revenue"]=> string(5) "18409" ["seller"]=> string(6) "Samuel" }
}
Estoy trabajando con la matriz anterior. Esta matriz multidimensional se llama $stats
.
Me gustaría ordenar esta matriz, por la cantidad.
De modo que el array multidim tiene su primer array 1016 luego 1018, 1017 y así sucesivamente.
He hecho esto por:
function compare($x, $y) {
if ( $x['quantity'] == $y['quantity'] )
return 0;
else if ( $x['quantity'] > $y['quantity'] )
return -1;
else
return 1;
}
usort($stats, 'compare');
Que funciona muy bien!
Pero el problema es que el índice de matriz principal (los ID, 1019, 1018, 1017, etc.) desaparece cuando se ordena. Me gustaría mantener la matriz índices.
¿Cómo puedo hacer esto?
27
1 answers
Creo que lo que necesitas es uasort
-
Ordena una matriz con una función de comparación definida por el usuario y mantiene la asociación del índice
Ejemplo
uasort($stats, 'compare');
84
Author: Baba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-16 22:09:24
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-16 22:09:24