Page 1 of 1
sorting multidimensional array
Posted: Thu Jan 12, 2006 8:06 pm
by fendtele83
ok so this is how im populating this array
Code: Select all
for($x=$x; $row = mysql_fetch_array($result); $x++)
{
$info_array[$x][$primary_key] = $row[$primary_key];
$info_array[$x]['title'] = $row['title'];
$info_array[$x]['start_date'] = $row["date_format(start_date, '%m-%d-%Y')"];
$info_array[$x]['city'] = $row['city'];
$info_array[$x]['state'] = $row['state'];
$info_array[$x]['venue'] = $row['venue'];
$info_array[$x]['register_form'] = $row['register_form'];
}
i want to sort it by $info_array[$x]['start_date']
how do i do that??
Posted: Thu Jan 12, 2006 8:37 pm
by timvw
Might want to have a look at
http://www.php.net/array_multisort.
But i see that you are fetching from a mysql resultset.. So i ask myself: Why don't you let mysql sort for you?
Posted: Thu Jan 12, 2006 10:33 pm
by fendtele83
because i'm using 2 queries at 2 different times and putting them into the same array... so i can't use mysql to sort it for me... and i was looking at the array_multisort function but i can't seem to figure it out... i know it's one of those things that as soon as i see how its applied to my problem, im going to be like... "damn, i coulda figured that out..."
Posted: Thu Jan 12, 2006 10:48 pm
by josh
two different times as in the page? you could union the results then sort it
Posted: Fri Jan 13, 2006 10:45 am
by pickle
array_multisort() is powerful, but obscure (IMO). For your situation, you want to make a second array that that uses $x as the keys, and start_date as the values. If you send that array to
array_multisort() along with $info_array,
array_multisort() will make the keys in $info_array match up with the keys in your second array. This should work:
Code: Select all
foreach($info_array as $key=>$properties)
{
$sort_array[$key] = $properties['start_date'];
}
array_multisort($sort_array,SORT_DESC,SORT_NUMERIC,$info_array);
May I suggest something about your query? Don't format the date in MySQL. You can always format it in PHP. Plus, it makes sorting a lot simpler.
Posted: Fri Jan 13, 2006 12:40 pm
by fendtele83
ok, now my next problem is how do i print all of the info out in the new order?? i really just don't understand how this works at all.
Posted: Fri Jan 13, 2006 1:03 pm
by John Cartwright
Nested foreach statements is one way..
Posted: Fri Jan 13, 2006 2:06 pm
by pickle
print_r() would dump the array.
Posted: Fri Jan 13, 2006 3:10 pm
by fendtele83
Code: Select all
foreach($info_array as $key=>$properties)
{
$sort_array[$key] = $properties['start_date'];
}
print_r(array_multisort($sort_array,SORT_DESC,SORT_NUMERIC,$info_array));
returns : 1
not the array...
Posted: Fri Jan 13, 2006 3:18 pm
by timvw
I would have expected you know why this is, as it's one of the first sentences on
http://www.php.net/array_multisort.
bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )
Returns TRUE on success or FALSE on failure.