开发者

Sort multi-dimensional array by child key date?

I have the following array:

[0] => Array
        (
            [name] => The Name
            [description] => description
            [date] => Thur, May 5 @ 7:00 p.m.
            [rating] => PG
            [year] => 2011
        )

[1] => Array
        (
            [name] => Name 2
            [description] => description 2
            [date] => Sun, May 8 @ 7:30 p.m.
            [rating] => 14A
            [year] => 2011
        )

There are about 5-10 more parts.

What I'm ultimately wanting to do is to use the date part of the array to group these items by day (I.e., "all items with "date" falling into "May 8" should be grouped as such).

Any idea how I'd go 开发者_开发问答about this? Note that the "date" field is stored as such in DB -- that's not a timestamp converted from date(); or whatever.

Many thanks!


Create your own sort function and call it using usort.

For example (not considering the intricacies of your timestamp format):

function date_sort($a, $b) {
  return strcmp($a['date'], $b['date']); //only doing string comparison
}

usort($array, 'date_sort');

To complete date_sort, you'll somehow need to convert the dates to comparable types. Here's a solution which converts them to UNIX timestamps:

function convert_date($time) {
  $time = substr($time, strpos($time, ',')+1);
  $time = str_replace('@', ',', $time);
  $time = str_replace('.', '', $time);
  return strtotime($time);
}

function date_sort($a, $b) {
  $a = convert_date($a['date']);
  $b = convert_date($b['date']);

  if ($a == $b) {
    return 0;
  }
  return ($a < $b) ? -1 : 1;
}


Use @Emil Vikström solution, with strtotime as comparing function

function date_sort($a, $b) {

$a = strtotime($a['date']); $b = strtotime($b['date']);

return ($a == $b) ? 0 : ($a>$b ? - 1 : 1);

}

usort($array, 'date_sort');

http://fr2.php.net/manual/en/function.strtotime.php should deal with most textual dates written in english.


Try this

$arrArray has array you have specified;

$newArray = array();
foreach($arrArray as $key => $value){

    $date1 = substr($value['date'], 0, strpos($value['date'],'@')-1);
    $newArray[$date1][] = $value;


}
print_r($newArray);


For grouping your data by date, run this little loop

$sortedArray = array();
foreach($dataListing as $data){
     //parse your $date field with an reg exp and transform it into integer with format MMDD
     $sortedArray[$dateIntegerFormated][] = $data;
}
ksort($sortedArray);
$sortedArray = array_values($sortedArray);

And you can use usort for sorting by time into each group

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜