Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by php array

Tags:

date

php

sorting

I need to sort the notification array by the value 'start_date' DESC order from the getNotifications function:

$posts_id_arr = getPoststIds($conn);

foreach ($posts_id_arr as $key => $val) {
  $total_arr[$key] = [
    'notification' => getNotifications($val['post_id'], $user_id, $conn)
  ];
}

$response_array = array('data' => $total_arr, 'more things' => $more_array);
echo json_encode($response_array);

right now the order is by post id due to the foreach loop.

data {
       notification: 
      [
       {
        post_id: “1",
        start_date: "2016-10-10 08:00:00",
       },
       {
        post_id: “1",
        start_date: "2016-10-10 12:00:00",
       }
    ],
     notification:
      [
        post_id: “2",
        start_date: "2016-10-10 09:00:00",
       },
       {
        post_id: “2",
        start_date: "2016-10-10 13:00:00",
       }
    ]
}

And i need it to be 1: 08:00, 2: 09:00, 1: 12:00, 2: 13:00

like image 991
Gilad Adar Avatar asked Oct 10 '16 07:10

Gilad Adar


People also ask

How do you sort an array in PHP?

PHP - Sort Functions For Arraysrsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.

What is Asort () and arsort ()?

Definition and UsageThe arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

What does sort () do in PHP?

Definition and Usage. The sort() function sorts an indexed array in ascending order. Tip: Use the rsort() function to sort an indexed array in descending order.

How do you sort data in an array?

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

You can use a custom function to sort the values in the array using uasort. Your date format is sortable using strcmp - a date in the past is lower than a date in the future, so you can use this in your comparator.

function sort_by_date($a, $b) {
  return strcmp($a->start_date, $b->start_date);
}

$sorted_posts = uasort($total_arr->notification, 'sort_by_date');

$response_array = array('data' => $sorted_posts, 'more things' => $more_array);
like image 101
iblamefish Avatar answered Sep 22 '22 13:09

iblamefish