Page 1 of 1

Arrays: Do x to y AND z

Posted: Wed Jan 19, 2011 10:28 am
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?

Re: Arrays: Do x to y AND z

Posted: Wed Jan 19, 2011 11:02 am
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

Re: Arrays: Do x to y AND z

Posted: Wed Jan 19, 2011 12:55 pm
by mikecampbell
Try the array_multisort function, which takes multiple arrays as parameters.

Code: Select all

array_multisort($favcolors, $names, $apsswords);

Re: Arrays: Do x to y AND z

Posted: Wed Jan 19, 2011 1:08 pm
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...