PHP: arsort - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

asort array

Last updated: Sat, 27 Jan 2007

view this page in

# arsort

(PHP 3, PHP 4, PHP 5)

arsort -- Отсортировать массив в обратном порядке, сохраняя ключи

## Описание

bool arsort ( array &array [, int sort_flags] )

Эта функция сортирует массив в обратном порядке таким образом, что сохраняются отношения между ключами и значениями. Она полезна, в основном, при сортировке ассаоциативных массивов, когда важно сохранить отношение ключ => значение.

Возвращает `TRUE` в случае успешного завершения или `FALSE` в случае возникновения ошибки.

Пример 1. Пример использования arsort()

`<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "$key = $val\n";
}
?>`

Результат выполнения данного примера:

    a = orange
    d = lemon
    b = banana
    c = apple

Названия фруктов были отсортированы в обратном порядке и отношения ключ/значение были сохранены.

Вы можете изменить поведение сортировки, используя дополнительный параметр `sort_flags`, подробнее см. sort().

См. также asort(), rsort(), ksort() и sort().

add a note User Contributed Notes
arsort
Scott Woods
02-Feb-2005 08:21
`Note about "morgan at anomalyinc dot com"'s comment:
As of PHP4, you can just use array_multisort() to sort parallel or multi-dimensional arrays.`
rodders_plonker at yahoo dot com
21-Aug-2000 06:43
`I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.
Made my day :).
Rodders.`
morgan at anomalyinc dot com
24-Nov-1999 07:30
`If you need to sort a multi-demension array, for example, an array such as
$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]
and you have say, 100 teams here, and want to sort by "TeamPoints":
first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo`
add a note
asort array

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST