Share the PHP array sorting sort, asort and ksort usage, sort, asort is briefly demonstrated in the example The usage of ksort is provided with comments to explain in detail.
Usage of sort, asort and ksort in PHP array sorting.
<?<span>php </span><span>$arr</span> = <span>array</span>('d'=>'sdf', 'r'=>'sdf', 'a'=> 'eee'<span>); </span><span>//</span><span>sort($arr); // 对数组的值进行重排, 删除之前的键值, 变为索引数组 //asort($arr); // 对数组按照值进行重排,并保持索引关系,索引数组和关联数组均适用</span> <span>ksort</span>(<span>$arr</span>); <span>//</span><span> 对数组按照键值进行重排,并保持索引关系,索引数组和关联数组均适用 // 对应逆序还有rsort arsort krsort // 使用函数比较有usort uksort uasort 第二个参数为比较的函数 需要在第一个参数相等 小于 大于第二个参数时 返回 等于 小于 大于 0 的值 浮点数只会取整数部分</span> // www.jbxue.com <span>print_r</span>(<span>$arr</span><span>); </span>?>
The example in this article only demonstrates the usage of ksort. You can test the running results of sort and asort to deepen your impression and have a firm grasp.
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 '
';
}
?>
In fact, it is helpful to read more PHP manuals. What are the forward and reverse order mentioned by LZ used for? If used directly on an array:
Sort the array by key name: ksort($array)
Sort the array in reverse order by key name: krsort($array)
Sort the array and keep the index relationship: asort($array)
Sort the array in reverse and keep the index relationship: asort($array)
Sort the array in reverse: rsort
Sort the array: sort