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?
Arrays: Do x to y AND z
Moderator: General Moderators
- 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
Combine the three arrays into a multidimensional associative array.
Then you can sort the list.
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
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]
);
}Code: Select all
function mySort($x, $y) {
return strcmp($x['favcolor'], $y['favcolor']);
}
usort($users, 'mySort');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
Try the array_multisort function, which takes multiple arrays as parameters.
Code: Select all
array_multisort($favcolors, $names, $apsswords);- 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
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...