View Full Version : having problems with sort();

08-28-2007, 01:18 AM
I'm having trouble with sort(); I can't seem to get it to work...

Now, I just typed this up... Just psedocode, although it *might* actually work! lol! Do I have the right idea? I haven't had any luck getting sort to do anything yet... Do I need to create a multidimensional array or something?

And no, I can't use ASC, or DESC!

//Nearly the exact same as a normal MySQL query, EXCEPT I CANT USE ASC, or DESC!!!!!
$friends = $facebook->api_client->fql_query("SELECT uid, name, pic_square FROM user");

$uids = array();
$names = array();
$pics = array();

foreach ($friends as $friend) {
push($uids, $friend['uid']);
push($names, $friend['name']); //The data is all strings just like a normal name, eg: John Smith
push($pics, $friend['pic_square']);

//Now, can I just use this sort to sort the names alphabetically
//and keep the uid's and pics in-line with the name like this?


//Now, this should return the three correct
// values for the person with the highest alphabetical name... Eg: Andrew Smith
echo $names[0] . $uids[0] . $pics[0];

//This would return the second, say there was only one person who's name started with a, and one with b.
echo $names[1] . $uids[1] . $pics[1];
//Would return Bart Smith, his uid, and pic.

08-28-2007, 01:42 AM
You're separating a mulit-dimensional array into three separate arrays, sorting one of those new arrays, and exactly how do you expect the other two arrays to magically get sorted in the same order as the one array you're sorting?

No, that won't work. You shouldn't create three different arrays. Simply sort the multi-dimensional array by name. Here's a pretty easy way to do that:

//create temporary array based on the array element you want to sort by
foreach ($friends as $key => $val) {
$sortValues[$key] = $val['name'];

//sort the temporary array
asort ($sortValues);

//build sorted array based on original array, in the order of temporary array
reset ($sortValues);
while (list ($arrayKey, $arrayVal) = each ($sortValues)) {
$sortedArray[] = $friends[$arrayKey];

//assign sorted array to original array
$friends = $sortedArray;