asort
(PHP 4, PHP 5, PHP 7, PHP 8)
asort — 連想キーと要素との関係を維持しつつ配列を昇順にソートする
説明
配列のキーと要素との関係を維持しつつ、
array
を昇順にソートします。
この関数は、 主に実際の要素の並び方が重要である連想配列をソートするために使われます。
注意:
比較結果が等しくなる二つの要素があった場合、それらの並び順は保持されます。PHP 8.0.0 より前のバージョンでは、ソートした配列におけるそれらの並び順は不定でした。
注意:
この関数をコールすると、配列の内部ポインタは最初の要素にリセットされます。
パラメータ
array
-
入力の配列。
flags
-
オプションの第二引数
flags
によりソートの動作を修正可能です。 使える値は下記の通りです:ソートタイプのフラグ:
-
SORT_REGULAR
- 通常通りに項目を比較します。 詳細は 比較演算子 で説明されています。 -
SORT_NUMERIC
- 数値として項目を比較します。 -
SORT_STRING
- 文字列として項目を比較します。 -
SORT_LOCALE_STRING
- 現在のロケールに基づいて、文字列として項目を比較します。 比較に使うロケールは、setlocale() 関数で変更できます。 -
SORT_NATURAL
- 要素の比較を文字列として行い、 natsort() と同様の「自然順」で比較します。 -
SORT_FLAG_CASE
-SORT_STRING
やSORT_NATURAL
と (ビットORで) 組み合わせて使い、 文字列のソートで大文字小文字を区別しないようにします。
-
戻り値
常に true
を返します。
例
例1 asort() の例
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
上の例の出力は以下となります。
c = apple b = banana d = lemon a = orange
fruits はアルファベットの昇順にソートされ、 各要素とキーとの関係は維持されます。
参考
- sort() - 配列を昇順にソートする
- arsort() - 連想キーと要素との関係を維持しつつ配列を降順にソートする
- 配列ソート関数の比較
+add a note
User Contributed Notes 31 notes
nick ([AT]) nickyost ([DOT]) com ¶
13 years ago
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.
This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.
Therefore, do something elegant like this:
<?php
// Sort the multidimensional array
usort($results, "custom_sort");
// Define the custom sort function
function custom_sort($a,$b) {
return $a['some_sub_var']>$b['some_sub_var'];
}
?>
This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.
Hope it helps!
aditycse at gmail dot com ¶
9 years ago
/*
* Name : Aditya Mehrotra
* Email: aditycse@gmail.com
*/
//Example for sorting by values for an alphanumeric array also having case-sensitive data
$exampleArray1 = $exampleArray2 = array(
0 => 'example1',
1 => 'Example10',
2 => 'example12',
3 => 'Example2',
4 => 'example3',
5 => 'EXAMPLE10',
6 => 'example10'
);
//default sorting
asort($exampleArray1);
// alphanumeric with case-sensitive data sorting by values
asort($exampleArray2, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
//output of defaut sorting
print_r($exampleArray1);
/*
* output of default sorting
Array
(
[5] => EXAMPLE10
[1] => Example10
[3] => Example2
[0] => example1
[6] => example10
[2] => example12
[4] => example3
)
*/
print_r($exampleArray2);
/*
* output of alphanumeric with case-sensitive data sorting by values
Array
(
[0] => example1
[3] => Example2
[4] => example3
[5] => EXAMPLE10
[1] => Example10
[6] => example10
[2] => example12
)
*/
richard at happymango dot me dot uk ¶
18 years ago
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.
It is usefull for sorting query results from a database by a particular field after the query has been returned
This function can be quite greedy. It recreates the array as a hash to use ksort() then back again
By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending
<?php
function record_sort($records, $field, $reverse=false)
{
$hash = array();
foreach($records as $record)
{
$hash[$record[$field]] = $record;
}
($reverse)? krsort($hash) : ksort($hash);
$records = array();
foreach($hash as $record)
{
$records []= $record;
}
return $records;
}
// Example below
$airports = array
(
array( "code" => "LHR", "name" => "Heathrow" ),
array( "code" => "LGW", "name" => "Gatwick" ),
);
printf("Before: <pre>%s</pre>", print_r($airports, true));
$airports = record_sort($airports, "name");
printf("After: <pre>%s</pre>", print_r($airports, true));
?>
Example Outputs:
Before: Array
(
[0] => Array ( [code] => LHR, [name] => Heathrow )
[1] => Array ( [code] => LGW, [name] => Gatwick )
)
After: Array
(
[0] => Array ( [code] => LGW, [name] => Gatwick )
[1] => Array ( [code] => LHR, [name] => Heathrow )
)
mike at clear-link dot com ¶
16 years ago
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.
<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
if ($valrev) { arsort($array); } else { asort($array); }
$vals = array_count_values($array);
$i = 0;
foreach ($vals AS $val=>$num) {
$first = array_splice($array,0,$i);
$tmp = array_splice($array,0,$num);
if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
$array = array_merge($first,$tmp,$array);
unset($tmp);
$i = $num;
}
}
// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);
// Standard asort
asort($tmp);
print_r($tmp);
// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);
// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);
// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);
// Results
Array
(
[pe] => 1
[ca] => 1
[ce] => 1
[cb] => 2
[pa] => 2
)
Array
(
[ca] => 1
[ce] => 1
[pe] => 1
[cb] => 2
[pa] => 2
)
Array
(
[cb] => 2
[pa] => 2
[ca] => 1
[ce] => 1
[pe] => 1
)
Array
(
[pa] => 2
[cb] => 2
[pe] => 1
[ce] => 1
[ca] => 1
)
sweetland at whoadammit dot com ¶
24 years ago
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
** comesafter ($s1, $s2)
**
** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
**/
function comesafter ($s1, $s2) {
/**
** We don't want to overstep the bounds of one of the strings and segfault,
** so let's see which one is shorter.
**/
$order = 1;
if (strlen ($s1) > strlen ($s2)) {
$temp = $s1;
$s1 = $s2;
$s2 = $temp;
$order = 0;
}
for ($index = 0; $index < strlen ($s1); $index++) {
/**
** $s1 comes after $s2
**/
if ($s1[$index] > $s2[$index]) return ($order);
/**
** $s1 comes before $s2
**/
if ($s1[$index] < $s2[$index]) return (1 - $order);
}
/**
** Special case in which $s1 is a substring of $s2
**/
return ($order);
}
/**
** asortbyindex ($sortarray, $index)
**
** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
** of the Ith member of both the group and user arrays is a string identifier. In the
** case of a user array this is the username; with the group array it is the group name.
** asortby
**/
function asortbyindex ($sortarray, $index) {
$lastindex = count ($sortarray) - 1;
for ($subindex = 0; $subindex < $lastindex; $subindex++) {
$lastiteration = $lastindex - $subindex;
for ($iteration = 0; $iteration < $lastiteration; $iteration++) {
$nextchar = 0;
if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
$temp = $sortarray[$iteration];
$sortarray[$iteration] = $sortarray[$iteration + 1];
$sortarray[$iteration + 1] = $temp;
}
}
}
return ($sortarray);
}
?>
It's a bit long with all the comments, but I hope it helps.
php at web-in-time dot com ¶
18 years ago
acecream's function works fine, especially with the spectre extension.
nevertheless sometimes the index values have to be kept. To achieve this, just replace:
$sorted_arr[] = $array[$arr_key];
with:
$sorted_arr[$arr_key] = $array[$arr_key];
mike at clear-link dot com ¶
16 years ago
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:
<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
if ($valrev) { arsort($array); } else { asort($array); }
$vals = array_count_values($array);
$i = 0;
foreach ($vals AS $val=>$num) {
$first = array_splice($array,0,$i);
$tmp = array_splice($array,0,$num);
if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
$array = array_merge($first,$tmp,$array);
unset($tmp);
$i = $i+$num;
// Fixed from previous post: $i = $num;
}
}
?>
mbevan at marginsoftware dot com ¶
22 years ago
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
jacko at kring dot co dot uk ¶
24 years ago
asort has one anoying feature, it ignores any default or implicit order in the data. i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.
richard at happymango dot me dot uk ¶
18 years ago
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.
<?php
function record_sort($records, $field, $reverse=false)
{
$hash = array();
foreach($records as $key => $record)
{
$hash[$record[$field].$key] = $record;
}
($reverse)? krsort($hash) : ksort($hash);
$records = array();
foreach($hash as $record)
{
$records []= $record;
}
return $records;
}
?>
freeman at generalresources dot com ¶
23 years ago
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
rojaro ¶
20 years ago
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.
<?php
function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
if(is_array($array) && count($array)>0) {
foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
else {
($case_sensitive)? natsort($temp) : natcasesort($temp);
if($order!='asc') $temp=array_reverse($temp,TRUE);
}
foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
return $sorted;
}
return $array;
}
?>
Anon ¶
13 years ago
Case insensitive sort in one line:
<?php
array_multisort(array_map('strtolower', $array), $array);
?>
rcwang at cmu dot edu ¶
22 years ago
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.
<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
while (list($firstIndex, ) = each($multiArray))
$indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
asort($indexMap);
while (list($firstIndex, ) = each($indexMap))
if (is_numeric($firstIndex))
$sortedArray[] = $multiArray[$firstIndex];
else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
return $sortedArray;
}
?>
salchicha at cable dot net dot co ¶
22 years ago
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:
<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
$tarr = array();
$rarr = array();
for($i = 0; $i < count($arr); $i++) {
$element = $arr[$i];
$tarr[] = strtolower($element->{$var});
}
reset($tarr);
asort($tarr);
$karr = array_keys($tarr);
for($i = 0; $i < count($tarr); $i++) {
$rarr[] = $arr[intval($karr[$i])];
}
return $rarr;
}
?>
It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.