如何在php中对关联数组进行排序 [英] How to sort an associative array in php

查看:53
本文介绍了如何在php中对关联数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 mysql 表,即

<前>身份证 ||乙 || |d |ud_id1 |20|8 |45|18|1

现在我想在 php 中检索该数据对数组进行排序并找到本示例中的最高字段 (c=45)

<前>$query="SELECT `a`, `b`, `c`, `d` from table where ud_id=1";$rs=mysql_query($query) 或 die(mysql_error());$row=mysql_fetch_array($rs);

但是我怎样才能对这个关联数组进行排序并找到最高的键呢?

解决方案

PHP 有一大堆排序功能.

听起来你想要的是asort()

其他替代方法请参见 PHP 手册,例如 sort()ksort()natsort()usort() 以及许多其他变体.还有 shuffle() 可以随机排序.

好的,逐步从数组中获取最大值:

asort($row);//或 arsort() 用于逆序,如果您愿意.结束($行);//将数组指针定位到最后一个元素.打印当前($row);//打印45",因为它是排序后的最高值.打印键($row);//打印c",因为它是最高排序值的键.

还有很多其他方法可以做到这一点.

I have mysql table i.e

id | a | b | c | d |ud_id
 1 | 20| 8 | 45| 18| 1

Now I want to retrieve that data in php sort the array and find the highest field in this example (c=45)

$query="SELECT `a`, `b`, `c`, `d` from table where ud_id=1";
$rs=mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($rs);

But how can I sort this associative array and find the highest key?

解决方案

PHP has a whole bunch of sorting functions.

The one is sounds like you want is asort()

See the PHP manual for the other alternatives such as sort(), ksort(), natsort(), usort(), and a number of other variations. There's also shuffle() to sort randomly.

[EDIT] Okay, step-by-step to get the highest value out of the array:

asort($row);  //or arsort() for reverse order, if you prefer.
end($row);  //positions the array pointer to the last element.
print current($row); //prints "45" because it's the sorted highest value.
print key($row); //prints "c" because it's the key of the hightst sorted value.

There are a whole bunch of other ways to do it as well.

这篇关于如何在php中对关联数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆