Reputation: 1003
I have a two array like this.
$array5 = json_decode('[{"time":"12:08 PM","md5":1201},{"time":"01:00 PM","md5":1121},{"day":"03:03 PM","md5":1401},{"time":"03:36 PM","md5":1334}]
',true);
$array6 = json_decode('[{"time":"12:08 PM","ips":20},{"time":"01:00 PM","ips":10},{"time":"03:02 PM","ips":12},{"time":"03:36 PM","ips":11}]', true);
combined array using array_merge_recursive is:
[{"time":"12:08 PM","url":1201,"ips":20},{"time":"01:00 PM","url":1121,"ips":10},{"time":"03:03 PM","url":1401},{"time":"03:36 PM","url":1334,"ips":11},{"time":"03:02 PM","ips":12}]
Now i want to sort this array according to time.Is there any possible to way to sort this array according to time?
Upvotes: 2
Views: 4061
Reputation: 16436
You can use usort
function of PHP
<?php
$arr_json = '[{"time":"12:08 PM","url":1201,"ips":20},{"time":"01:00 PM","url":1121,"ips":10},{"time":"03:03 PM","url":1401},{"time":"03:36 PM","url":1334,"ips":11},{"time":"03:02 PM","ips":12}]';
$arr = json_decode($arr_json,true);
function sort_by_time($a,$b)
{
$a_time = strtotime($a['time']);
$b_time = strtotime($b['time']);
return $a_time > $b_time;
}
usort($arr, "sort_by_time");
print_r($arr);
Upvotes: 1
Reputation: 181
You may use Laravel array_sort helper method https://laravel.com/docs/5.4/helpers#method-array-sort
To avoid errors during comparison, use dates as Carbon opjects http://carbon.nesbot.com/docs/
$array = array_values(array_sort($array, function ($value) {
return new Carbon($value['time']);
}));
Upvotes: 5