Ordenar Matriz Multidimensional por Valor
¿Cómo puedo ordenar esta matriz por el valor de la clave "order"? Aunque los valores son actualmente secuenciales, no siempre lo serán.
Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
9 answers
Pruebe un usort , si todavía está en PHP 5.2 o anterior, primero tendrá que definir una función de ordenación:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
A partir de PHP 5.3, puede usar una función anónima:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
Y finalmente con PHP 7 puedes usar el operador de nave espacial :
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Para extender esto a la ordenación multidimensional, haga referencia al segundo/tercer elemento de ordenación si el primero es cero-mejor explicado a continuación. También puede utilizar esto para ordenar en subelementos.
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
Si necesita conservar las asociaciones de claves, use uasort()
- consulte comparación de las funciones de ordenación de matrices en el manual
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
2018-09-15 00:36:02
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"order");
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
2010-04-23 13:57:03
Utilizo esta función :
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column($array, 'order');
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
2010-04-23 14:03:47
Normalmente uso usort, y paso mi propia función de comparación. En este caso, es muy simple:
function compareOrder($a, $b)
{
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
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
2016-02-16 06:36:40
$sort = array();
$array_lowercase = array_map('strtolower', $array_to_be_sorted);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);
Esto se encarga de los alfabetos en mayúsculas y minúsculas.
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-02-22 21:05:12
Para ordenar el array por el valor de la clave" title " use:
uasort($myArray, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
Strcmp compara las cadenas.
Uasort () mantiene las claves del array tal como fueron definidas.
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
2018-03-13 10:40:39
Un enfoque para lograr esto sería así
$new = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3,
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2,
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1,
],
];
$keys = array_column($new, 'order');
$result = array_multisort($keys, SORT_ASC, $new);
Resultado:
Array
(
[0] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
)
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
2018-07-04 13:30:26
El enfoque más flexible sería utilizar este método
Arr::sortByKeys(array $array, $keys, bool $assoc = true): array
He aquí por qué:
Puede ordenar por cualquier clave (también anidada como
'key1.key2.key3'
o['k1', 'k2', 'k3']
)-
Funciona tanto en matrices asociativas como no asociativas (
$assoc
flag) -
No utiliza reference-return nuevo array ordenado
En su caso sería tan simple como:
$sortedArray = Arr::sortByKeys($array, 'order');
Este método es parte de esta biblioteca.
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
2018-09-06 18:10:57
Seamos sinceros: php NO tiene una simple función lista para usar para manejar correctamente cada escenario de ordenación de matrices.
Esta rutina es intuitiva, lo que significa una depuración y mantenimiento más rápidos:
// automatic population of array
$tempArray = array();
$annotations = array();
// ... some code
// SQL $sql retrieves result array $result
// $row[0] is the ID, but is populated out of order (comes from
// multiple selects populating various dimensions for the same DATE
// for example
while($row = mysql_fetch_array($result)) {
$needle = $row[0];
arrayIndexes($needle); // create a parallel array with IDs only
$annotations[$needle]['someDimension'] = $row[1]; // whatever
}
asort($tempArray);
foreach ($tempArray as $arrayKey) {
$dataInOrder = $annotations[$arrayKey]['someDimension'];
// .... more code
}
function arrayIndexes ($needle) {
global $tempArray;
if (!in_array($needle,$tempArray)) {
array_push($tempArray,$needle);
}
}
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
2018-04-03 16:26:04