简体   繁体   English

如何在php中按字母顺序对关联数组进行排序?

[英]How to sort an associative array alphabetically in php?

I am getting my array values from database. 我从数据库获取数组值。 and it is just names of users. 它只是用户名。 Iam printing them as it as they are retrieved , I want to print them Alphabetical order of their names (Ascending Order). 我要在检索时按它们的顺序打印它们,我想按名称的字母顺序(升序)打印它们。 How can I do this ? 我怎样才能做到这一点 ?

foreach($common_follows as $row) // $common_follows contains the IDs of users
            {

        $names=$obj2->get_user_name($row); //this function gets the name from user ID

                    while   ($rows = mysql_fetch_assoc($names)) // For getting the name of the person being followed
                    {
                sort($rows['name']); //Not seems to sort
                        echo '<img src="https://graph.facebook.com/'.$rows['user_id'].'/picture?type=normal" width="65" height="20" id="fbthumb">';
                        echo $rows['name']."<br>";
                      $count_common++;
                    }
            }

That sort function does not seem to work , since at each loop iteration a single name is returned . 该排序功能似乎不起作用,因为在每次循环迭代时都返回一个名称。

You can sort a PHP array by key using ksort . 您可以使用ksort按键对PHP数组进行排序。 if you want to sort by value, use asort . 如果要按值排序,请使用asort

If you wanted to move the sorting to your MySQL you could do it like so: 如果您想将排序移至MySQL,可以这样进行:

SELECT *
FROM users
ORDER BY name ASC

This is only an example you'll need to match your table/column names. 这仅是您需要匹配表/列名称的一个示例。

With your example code you could make $common_follows into a comma separated string ie 1,2,3... and pass that into the query rather than looping and making multiple MySQL queries. 使用示例代码,您可以将$common_follows制成逗号分隔的字符串,即1,2,3...并将其传递给查询,而不是循环并进行多个MySQL查询。 This would look like the following: 如下所示:

SELECT *
FROM users
WHERE id IN (1,2,3) // <-- comma separated string
ORDER BY name ASC
<?php

 $fruits = array("lemon", "orange", "banana", "apple");
  sort($fruits);
 foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}

  ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM