Jak posortować 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
)
)
12 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');
W PHP 7 za pomocą operatora kosmicznego:
usort($array, function($a, $b) {
return $a['order'] <=> $b['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
2020-05-07 00:55:28
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');
array_multisort($keys, SORT_ASC, $new);
var_dump($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
2019-06-27 10:07:26
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
$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
Użycie array_multisort()
, array_map()
array_multisort(array_map(function($element) {
return $element['order'];
}, $array), SORT_ASC, $array);
print_r($array);
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
2020-02-25 15:25: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
Jeśli ktoś potrzebuje sortowania według klucza najlepiej użyć poniżej
usort($array, build_sorter('order'));
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
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
2020-09-01 07:39:45
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
To rozwiązanie jest dla usort() z łatwą do zapamiętania notacją do sortowania wielowymiarowego. Używany jest operator statku kosmicznego, który jest dostępny od PHP 7.
usort($in,function($a,$b){
return $a['first'] <=> $b['first'] //first asc
?: $a['second'] <=> $b['second'] //second asc
?: $b['third'] <=> $a['third'] //third desc (a b swapped!)
//etc
;
});
Przykłady:
$in = [
['firstname' => 'Anton', 'surname' => 'Gruber', 'birthdate' => '03.08.1967', 'rank' => 3],
['firstname' => 'Anna', 'surname' => 'Egger', 'birthdate' => '04.01.1960', 'rank' => 1],
['firstname' => 'Paul', 'surname' => 'Mueller', 'birthdate' => '15.10.1971', 'rank' => 2],
['firstname' => 'Marie', 'surname' => 'Schmidt ', 'birthdate' => '24.12.1963', 'rank' => 2],
['firstname' => 'Emma', 'surname' => 'Mueller', 'birthdate' => '23.11.1969', 'rank' => 2],
];
Pierwsze zadanie: kolejność według rangi asc, nazwisko asc
usort($in,function($a,$b){
return $a['rank'] <=> $b['rank'] //first asc
?: $a['surname'] <=> $b['surname'] //second asc
;
});
Drugie zadanie: kolejność według rangi desc, nazwisko asc, firstmame asc
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: $a['surname'] <=> $b['surname'] //second asc
?: $a['firstname'] <=> $b['firstname'] //third asc
;
});
Trzecie zadanie: Uporządkuj według Rang desc, birthdate asc
Daty Nie można posortować w tej notacji. Jest on konwertowany za pomocą strtotime.
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: strtotime($a['birthdate']) <=> strtotime($b['birthdate']) //second asc
;
});
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
2021-01-28 14:36:24