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
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With