php 关联数组 排序,PHP怎么给关联数组进行排序?(代码示例)

本篇文章主要给大家介绍如何用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()函数对关联数组按照键名进行升序排序。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值