0

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 .

4
  • 3
    Why not do the ordering in the SQL query? Commented Jan 6, 2013 at 17:22
  • I am retrieving each name from its user_id. Sorting bu userid does not sort them alphabetically. How can I use that sort function ? Commented Jan 6, 2013 at 17:24
  • What's behind the foreach()? Commented Jan 6, 2013 at 17:35
  • it is the code that retrieves all user IDs from database and saves them to $common_follows array. Commented Jan 6, 2013 at 18:36

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
<?php

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

  ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.