Sortuj tablicę wielowymiarową według wartości
Jak mogę posortować tablicę według wartości klucza "order"? Chociaż wartości są obecnie sekwencyjne, nie zawsze będą.
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
Spróbuj użyć usort , jeśli nadal używasz PHP 5.2 lub wcześniejszego, musisz najpierw zdefiniować funkcję sortowania:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Począwszy od PHP 5.3, możesz użyć funkcji anonimowej:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
I na koniec z PHP 7 możesz użyć operatora kosmicznego :
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Aby rozszerzyć to na sortowanie wielowymiarowe, odwołaj się do drugiego / trzeciego elementu sortowania, jeśli pierwszy jest zerowy - najlepiej wyjaśnione poniżej. Możesz również użyć tego do sortowania na podelementy.
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;
});
Jeśli chcesz zachować skojarzenia kluczy, użyj uasort()
- patrz Porównanie funkcji sortowania tablic w instrukcji
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-23 13:57:03
Używam tej funkcji:
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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-23 14:03:47
Zwykle używam usort i przekazuję własną funkcję porównawczą. W tym przypadku jest to bardzo proste:
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/doraprojects.net/template/agent.layouts/content.php on line 54
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);
To zajmuje się zarówno dużymi, jak i małymi literami alfabetu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-22 21:05:12
Aby posortować tablicę według wartości klucza" title " użyj:
uasort($myArray, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
Strcmp porównaj łańcuchy.
Uasort () utrzymuje klucze tablicy tak, jak zostały zdefiniowane.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-13 10:40:39
Jedno podejście do osiągnięcia tego byłoby takie
$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);
Wynik:
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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-04 13:30:26
Najbardziej elastycznym podejściem byłoby użycie tej metody
Arr::sortByKeys(array $array, $keys, bool $assoc = true): array
Oto dlaczego:
Możesz sortować według dowolnego klucza (również zagnieżdżonego jak
'key1.key2.key3'
lub['k1', 'k2', 'k3']
)-
Działa zarówno na tablicach asocjacyjnych, jak i nie asocjacyjnych (znacznik
$assoc
) -
Nie używa referencji-zwraca nową sortowaną tablicę
W Twoim przypadku byłoby to tak proste jak:
$sortedArray = Arr::sortByKeys($array, 'order');
Ta metoda jest częścią tej biblioteki.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 18:10:57
Spójrzmy prawdzie w oczy: php nie posiada prostej funkcji out of the box, aby poprawnie obsługiwać każdy scenariusz sortowania tablic.
Ta procedura jest intuicyjna, co oznacza szybsze debugowanie i konserwację:
// 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 16:26:04