This article explains the usage of sort, asort and ksort in PHP array sorting with examples for your reference. Specific examples are as follows:
<?php $arr = array('d'=>'sdf', 'r'=>'sdf', 'a'=> 'eee'); //sort($arr); // 对数组的值进行重排, 删除之前的键值, 变为索引数组 //asort($arr); // 对数组按照值进行重排,并保持索引关系,索引数组和关联数组均适用 ksort($arr); // 对数组按照键值进行重排,并保持索引关系,索引数组和关联数组均适用 // 对应逆序还有rsort arsort krsort // 使用函数比较有usort uksort uasort 第二个参数为比较的函数 需要在第一个参数相等 小于 大于第二个参数时 返回 等于 小于 大于 0 的值 浮点数只会取整数部分 print_r($arr); ?>
The examples in this article only demonstrate the usage of ksort. Interested readers can test the running results of sort and asort to deepen their impression and have a firm grasp. I hope the examples in this article will be helpful to everyone in PHP programming.
I don’t know how you wrote it. It’s missing planet1, but you can do without it. Just use this 2. Also, use commas to separate the array, don’t use semicolons, and use points to end the statement. No. The following is what I changed. Take a look for yourself..
$planet2=array(
'X'=>'Earth',
'Y'=> 'Venus',
'Z'=>'Mars',
'A'=>'Jupiter',
'B'=>'Saturn',
);
asort($planet2);
echo 'Use function asort to sort array elements:';
echo '
';
foreach($ planet2 as $key => $value)
{
echo 'planet2['.$key.']='.$value;
echo '
';
echo '
';
}
echo '
';
echo 'Use function ksort to sort array elements: ';
echo '
';
ksort($planet2);
foreach($planet2 as $key=>$value)
{
echo 'planet2['.$key.' ]='.$value;
echo '
';
echo '
';
}
?>
a1, a12, a2, b1 The sort that comes with php should result in this.
He compares character by character.
If you want numbers like yours to be treated as a whole, you have to do it yourself.
Just make the array like this
For example,
array('a1','a2','a11','b1','b11')
is processed into
array(
'a'=>array(
1=>array('a1'),
2=>array('a2'),
11=>array( 'a11')
),
'b'=>array(
1=>array('b1'),
11=>array('b11')
)
)