Reputation: 394
I'm a newbie in PHP programming. I use a FQL query to get birthdays of all user's friends. But I want to sort the users according to month and day. Can this be possible in multidimensional arrays? I want:
$year = array('jan' => array('1' => array(data returned by fql query), '2' => array(data returned by fql query),..etc), 'feb' => array('1' => array(data returned by fql query)), 'mar' => array(), etc);
Is it possible? My code so far:
$query = "SELECT uid, first_name, last_name, birthday_date, sex, pic_square, current_location, hometown_location FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND strlen(birthday_date) != 0 ORDER BY birthday_date";
$year =array();
$prm = array(
'method' => 'fql.query',
'query' => $query,
'callback' => ''
);
$friends = $facebook->api($prm);
for($m = 1;$m <= 12;$m++){
$dm = mktime(0,0,0,$m,26);
$dm = date("M", $dm);
$year[] = $dm;
for($d = 1;$d <= 31;$d++){
$a2 = array($d => array());
$a3 = $out[$dm];
array_push($out,array($dm => array($d => "")));
}
}
PS: I want to be able to represent birthdays in each month in a div, order by day of month. Thanks.
Upvotes: 0
Views: 1318
Reputation: 736
multi_sort($myArray[index], SORT_NUMERIC, SORT_ASC) is what you are looking for, and you can get rid of the nested for loops. pass the array and index to be sorted by, sort numerically, and in SORT_ASC, or SORT_DESC depending on what you want. You may need to removed dashes or slashes from the dates first, experiment and find out.
Here is the PHP man page. http://php.net/manual/en/function.array-multisort.php
Upvotes: 1
Reputation: 2879
Or you could make the day/month an array key and sort based one that:
$sort = array();
foreach($friends as $friend)
{
// note the extra 0's here, to give us padding to filter out duplicate array keys
// this gives us an int in the format 030100, 093100, etc
$key = (int)date('Md00', strtotime($friend['birthday_date']));
// make sure we don't have duplicates...if the key already exists, incrememnt it by one
while(isset($sort[$key])) $key++;
$sort[$key] = $friend;
}
// sort the items by array key
ksort($sort);
// $sort now contains your friends, sorted by birthday.
Note that as mentioned, facebook allows you do do the sorting on their end, so it's best to let them do the work. There are some cases where post-query sorting is very useful, and this is generally how I like to do it.
Upvotes: 0