aendra
aendra

Reputation: 5346

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!

Upvotes: 3

Views: 4798

Answers (4)

Bil
Bil

Reputation: 543

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

Upvotes: 0

Poonam Bhatt
Poonam Bhatt

Reputation: 10322

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);

Upvotes: 0

Emil Vikström
Emil Vikström

Reputation: 91963

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;
}

Upvotes: 7

ts.
ts.

Reputation: 10709

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');

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

Upvotes: 2

Related Questions