user2250471
user2250471

Reputation: 1112

Sort iterations from within foreach loop

I have an array with user names:

$a = array('user1','user2');

I want to use them to output the users' information in a list, but I need it sorted by their name, which I pull from the database within the foreach loop that lists them. How do I sort it?

foreach($a as $b) {
    $user = $users->getUser($b); // gets user's details from the database
    $name = $user['name']; // I want the list to be sorted by this variable
    echo $name.'<br />';
}

The names aren't unique, for example user1 and user1 might both be named John Smith. Only the usernames are unique.

Upvotes: 0

Views: 165

Answers (2)

Karl
Karl

Reputation: 833

This should work. Now it sorts by the name key and loops through the users in a second loop.

function sortByName($a, $b) {
    if($a['name'] !== $b['name'])
        return ($a['name'] > $b['name']) 1 : -1;
}

$a = array('user1','user2');
$userList = array();

foreach($a as $b) {
    $userList[] = $users->getUser($b);
}

usort($userList, 'sortByName');

foreach($userList as $person) {
    echo $person['name'];
}

Upvotes: 1

Fabricator
Fabricator

Reputation: 12782

Use usort along with user defined comparator

<?php
$users = array();
foreach($a as $b) {
    $user = $users->getUser($b); // gets user's details from the database
    $users[] = $user;
}

usort($users, 'comp_user');
foreach ($users as $user) {
    $name = $user['name'];
    echo $name.'<br />';
}

function comp_user($u1, $u2)
{
    if ($u1['name'] == $u2['name']) {
        return 0;
    }
    return ($u1['name'] < $u2['name']) ? -1 : 1;
}

Upvotes: 1

Related Questions