Adry
Adry

Reputation: 307

Php arrays merging and sorting by date descent

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?

Upvotes: 0

Views: 1095

Answers (2)

Mohiuddin Sohel
Mohiuddin Sohel

Reputation: 78

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

}

Upvotes: 0

pevinkinel
pevinkinel

Reputation: 411

Nothing easier:

$h_pp_ps = array_reverse($h_pp_ps);

Upvotes: 1

Related Questions