b1919676
b1919676

Reputation: 110

Reorder array items depending on substring representing time in php

Hi buddies :) I'm required to reorder an array which contains several items with a given format. For example, like this:

m=11:00_12:00,d=10:00_10:30,a=13:00_13:30

As we can see, any item's given format is a string like x=whateverinitialhour_whateverfinalhour

As stated before, I have to reorder these items depending on initial hour, so the expected result should be:

d=10:00_10:30,m=11:00_12:00,a=13:00_13:30

Well, I have been searching a lot and found usort, and I found similar questions too like How to sort multidimensional PHP array (recent news time based implementation)

So, I'm coding this:

$arr = array();
$newarr = array();
$arr = ('m=11:00_12:00','d=10:00_10:30','a=13:00_13:30');
usort($arr, function($a,$b) {return strtotime(substr($a[0],2,5))-strtotime(substr($b[0],2,5));});
foreach ($arr as $value) {
    $newarr[] = $value;
}

Unfortunately, I'm not getting the expected result, and the new array contains this:

m=11:00_12:00,a=13:00_13:30,d=10:00_10:30

Which it is not reordered by every item's initial hour :(

What am I doing wrong? Am I not using usort in a rigth way? Thanks.

Upvotes: 0

Views: 29

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Look at your usort() function,

usort($arr, function($a,$b) {
    return strtotime(substr($a[0],2,5))-strtotime(substr($b[0],2,5));
                            ^^^^^                        ^^^^^
});

$a and $b are not arrays, they are elements of the array. Also, you don't need a new array to store the sorted array, usort() applies the manipulation in the original array itself. So your code should be like this:

$arr = array('m=11:00_12:00','d=10:00_10:30','a=13:00_13:30');
usort($arr, function($a,$b){ 
    return (strtotime(substr($a,2,5)) < strtotime(substr($b,2,5))) ? -1 : 1; 
});

var_dump($arr);

Upvotes: 1

Related Questions