登录  /  注册
PHP怎么给关联数组进行排序?(代码示例)
藏色散人
发布: 2023-04-04 11:48:01
原创
5086人浏览过

本篇文章主要给大家介绍如何用PHP给关联数组进行排序

对于PHP学习者来说,数组是一个非常重要的知识点,所谓数组就是能够在单独的变量名中存储一个或多个值。索引数组即带有数字索引的数组,关联数组即带有指定键的数组,多维数组即包含一个或多个数组的数组。

下面我们就通过简单的示例为大家介绍关联数组进行各种排序的方法。

代码示例如下:

<?php
echo "Associative array : Ascending order sort by value";
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); 
asort($array2);
foreach($array2 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "Associative array : Ascending order sort by Key";
$array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); 
ksort($array3);
foreach($array3 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."";
}
echo "Associative array : Descending order sorting by Value";
$age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
arsort($age);
foreach($age as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."";
}
echo "Associative array : Descending order sorting by Key";
$array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); 
krsort($array4);
foreach($array4 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
} 
?>
登录后复制

输出结果如下:

1、按值升序

Associative array : Ascending order sort by value   
Age of Sophia is : 31                                       
Age of William is : 39                                      
Age of Ramesh is : 40                                       
Age of Jacob is : 41
登录后复制

2、按照键名对关联数组进行升序排序:

Associative array : Ascending order sort by Key    
Age of Jacob is : 41                                        
Age of Ramesh is : 40                                       
Age of Sophia is : 31                                       
Age of William is : 39
登录后复制

3、按值降序

Associative array : Descending order sorting by Value 
Age of Jacob is : 41                                        
Age of Ramesh is : 40                                       
Age of William is : 39                                      
Age of Sophia is : 31
登录后复制

4、按照键名对关联数组进行降序排序:

Associative array : Descending order sorting by Key 
Age of William is : 39                                      
Age of Sophia is : 31                                       
Age of Ramesh is : 40  
Age of Jacob is : 41
登录后复制

相关函数介绍:

arsort() 函数对关联数组按照键值进行降序排序。

asort() 函数对关联数组按照键值进行升序排序。

krsort() 函数对关联数组按照键名进行降序排序。

ksort() 函数对关联数组按照键名进行升序排序。

本篇文章就是关于关联数组的排序方法介绍,希望对需要的朋友有所帮助!

以上就是PHP怎么给关联数组进行排序?(代码示例)的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学