2

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?

3
  • How did you retrieve the array in laravel can you explain ? Commented Aug 18, 2017 at 11:00
  • 2
    The posted text is JSON, not PHP code. Consequently, you don't have an array. Use json_decode() to create an array from it then use usort() to sort it as you please. Commented Aug 18, 2017 at 11:00
  • yes sure i will update my question Commented Aug 18, 2017 at 11:01

2 Answers 2

5

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']);
}));
Sign up to request clarification or add additional context in comments.

1 Comment

To manage order we may use - $value["time"] Also, it's possible to convert time to Carbon instance to avoid errors during comparisons
1

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

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.