Faizan
Faizan

Reputation: 1898

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 .

Upvotes: 0

Views: 1848

Answers (3)

Rocks
Rocks

Reputation: 511

<?php

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

  ?>

Upvotes: 0

diggersworld
diggersworld

Reputation: 13090

If you wanted to move the sorting to your MySQL you could do it like so:

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 i.e. 1,2,3... and pass that into the query rather than looping and making multiple MySQL queries. This would look like the following:

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

Upvotes: 1

abhi.gupta200297
abhi.gupta200297

Reputation: 891

You can sort a PHP array by key using ksort. if you want to sort by value, use asort.

Upvotes: 3

Related Questions