0

I need to combine 2 arrays coming from data base (each one ordered by date descent) and echo a new one together by date descent. Studying php sort functions I got to this code:

//Function
function dateSort($a,$b){
$dateA = strtotime($a['data']);
$dateB = $b['payment_date'];//already unixtime
return ($dateA-$dateB);
}

// Merge the arrays
$h_pp_ps = array_merge($h_pp,$h_ps);
// Sort the array using the call back function
usort($h_pp_ps, 'dateSort');
//PRINT!!
print_r($h_pp_ps);

This will produce results from low date to high.... how to get it from high to low?

1
  • Looks like this script was sources from: stackoverflow.com/a/9086669/2943403 If you want descending sorting, then swap the A and the B around. Better yet, use the more modern and stable spaceship operator: return $dateB <=> $dateA; array_reverse() is not a good, direct solution. Commented Apr 23, 2024 at 6:11

2 Answers 2

1

Nothing easier:

$h_pp_ps = array_reverse($h_pp_ps);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot for that one it probably should but somehow it's not working, it just does not make any effect
I marked the question solved with your suggestion because the error I was having was due to database results and I had to change approuch to the problem, although your was surely the answer for that question thanks a lot!
0

Subtract $dateA from $dateB such as ($dateB - $dateA) in the return statement of method 'dataSort', it will reverse the sorting order.

Details:

Change this method

function dateSort($a,$b){
$dateA = strtotime($a['data']);
$dateB = $b['payment_date'];//already unixtime
return ($dateA-$dateB);

}

To:

function dateSort($a,$b){
 $dateA = strtotime($a['data']);
 $dateB = $b['payment_date'];//already unixtime
 return ($dateB - $dateA);

}

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.