Arrays: Do x to y AND z

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Cucumberdude
Forum Newbie
Posts: 14
Joined: Sun Dec 12, 2010 11:53 pm

Arrays: Do x to y AND z

Post by Cucumberdude »

So I'm kinda new to PHP.

I'm working with a couple arrays and I want to be able to sort them. The only problem is, they correspond (ie, one array is 'Names', the other is 'Passwords', the other is 'Favorite Colour' etc). So, for example, I want to be able to sort 'Favorite Colour' alphabetically and then have the other arrays be sorted not alphabetically but the same way Fav Colour was such that they correspond.

I understand the sort() function, I just want to know what the best way to do this is. While looking into it, I stumbled upon multidimensional arrays. Is that what I want? or something else?
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Arrays: Do x to y AND z

Post by Jonah Bron »

Combine the three arrays into a multidimensional associative array.

Code: Select all

$names = array(/* ... */);
$passwords = array(/* ... */);
$favcolors = array(/* ... */);

$users = array();

foreach ($names as $key => $name) {
    $users[] = array(
        'name' => $names[$key],
        'password' => $passwords[$key],
        'favcolor' => $favcolors[$key]
    );
}
Then you can sort the list.

Code: Select all

function mySort($x, $y) {
    return strcmp($x['favcolor'], $y['favcolor']);
}
usort($users, 'mySort');
We have to use usort() instead of sort() because we're sorting by a sub-array. See the manual here:

http://php.net/usort
http://php.net/strcmp
mikecampbell
Forum Commoner
Posts: 38
Joined: Tue Oct 12, 2010 7:26 pm

Re: Arrays: Do x to y AND z

Post by mikecampbell »

Try the array_multisort function, which takes multiple arrays as parameters.

Code: Select all

array_multisort($favcolors, $names, $apsswords);
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Arrays: Do x to y AND z

Post by Jonah Bron »

Ah, great find. I didn't know about array_multisort (http://php.net/array-multisort). I still hold that it would be better to use a multidimensional associative array though...
Post Reply