-1

I am trying to fill an array with values:

foreach($pallets as $pallet){
  $i++;
  $orders[$i]['id'] = $pallet->id;
  $orders[$i]['reference'] = $pallet->reference;
  $orders[$i]['created_at'] = $pallet->created_at;
  $orders[$i]['status'] = $pallet->getStatus();
}

How can i order the values ($i) inside the array by their created_at attribute?

Many thanks

Ben
  • 8,894
  • 7
  • 44
  • 80
Jacob
  • 412
  • 7
  • 17
  • 2
    Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Ben Feb 18 '16 at 16:36

2 Answers2

0

Use usort (http://php.net/manual/en/function.usort.php):

function cmp($a, $b)
{
    if ($a["created_at"] == $b["created_at"]) {
        return 0;
    }
    return ($a["created_at"] < $b["created_at"]) ? -1 : 1;
}

usort($orders, "cmp");

foreach ($orders as $key => $value) {
    echo "$key: $value\n";
}
Blackbam
  • 17,496
  • 26
  • 97
  • 150
0

Extract the created_at column and sort that while sorting the original array the same:

array_multisort(array_column($orders, 'created_at'), SORT_ASC, $orders);

This assumes that created_at is in a format that sorts correctly such as 2016-02-18 12:00. If not, but if it is still a valid date/time try:

array_multisort(array_map('strtotime', array_column($orders, 'created_at')),
                SORT_ASC,
                $orders);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87