【问题标题】:How to sort an associative array in php如何在php中对关联数组进行排序
【发布时间】:2011-07-26 17:32:46
【问题描述】:

我有mysql表,即

编号 |一个 |乙 | c | d |ud_id 1 | 20| 8 | 45| 18| 1

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

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

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

【问题讨论】:

  • 您的数据库设计似乎有误。您必须使用 SQL 而不是 PHP 找到最高的
  • 同意弹片上校,桌子设计不适合这个。

标签: php mysql


【解决方案1】:

PHP 有一大堆排序函数。

你想要的是asort()

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

[编辑] 好的,一步一步从数组中取出最大值:

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.

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

【讨论】:

  • 当我使用 print_r(sort($row)); 这给了我结果 1 我想要像 ['c']=>45 这样的高键值
  • @source:好的,如果你按照我的建议尝试asort() 会怎样?
  • 好的,我使用asort($row); print_r($row),结果是Array ( [1] => 8 [b] => 8 [3] => 18 [d] => 18 [0] => 20 [a] => 20 [2] => 45 [c] => 45 ),那么我怎样才能从这个数组中获得最高值。
  • @source:查看我的编辑以了解一种方法。但是还有许多其他方法可以做同样的事情。
【解决方案2】:

就像@Spudley 所说,arsort 就是答案。您可以通过获取其array_keys 中的第一个来获取结果数组的第一个键。

// ...
$row = mysql_fetch_assoc ($rs);
arsort ($row);
$keys = array_keys ($row);
printf ("key: %s, value: %s", $keys[0], $row[$keys[0]]);

另请注意mysql_fetch_assoc

【讨论】:

  • 但是asort 对数组进行升序排序,并希望将其降序排序,以便在第一个偏移量上应该有最大值。
  • @source - 如果您阅读我链接到的手册 页面,您会看到 asort() 具有匹配函数 arsort() 来执行相同的排序以相反的顺序。
  • @Spudley 我想要的功能是arsort() 不是asort() 无论如何谢谢你
【解决方案3】:

您可以在查询中进行排序 - 请在此处查看 stackoverflow 答案: php, sort an array from mysql

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 2010-10-21
    • 2019-04-01
    • 2016-11-02
    • 2016-02-01
    • 1970-01-01
    • 2014-05-22
    • 2011-05-01
    相关资源
    最近更新 更多