There's an answer here: Combine two array and order this new array by date
It explains how two arrays can be merged and then sorted by date.
function cmp($a, $b){
$ad = strtotime($a['date']);
$bd = strtotime($b['date']);
return ($ad-$bd);
}
$arr = array_merge($array1, $array2);
usort($arr, 'cmp');
the solution looks quite elegant, but I'm confused by
return ($ad-$bd);
I mean there's no comparison operator, it just subtracts
function newFunc($a, $b) {
return($a-$b);
}
echo newFunc(5,3);
returns 2
So how does this actually indicate how to sort the arrays?
Update:
I read further the documentation on the usort page as suggested. Does it perform this subtraction with each of the elements? Does it iterate through each array element and subtracts it from other elements? Just trying to wrap my head around this.
To quote the documentation, a usort
's value_compare_func
is a function that:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
In this case, both dates are converted to a Unix timestamp, i.e., the number of seconds since the epoch. If $a
comes before $b
, it will have less seconds since the epoch, so subtracting it from $b
will return a negative number. If it comes after $b
, subtracting the two will return a positive number, and if they are the same, the subtraction will of course return zero.
If you read a manual, you see:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
By substracting values you get either positive or negative or 0 value, which allows to sort values.