Jump to content

Usort by value within array


ben03

Recommended Posts

Hi there,

I have been going in circles with this one and at times getting some sort of sorting but not working correctly.

I am trying to sort an array by a date that is set within, using strtotime:

$array = [0
	['promoOpening' => '27/12/2022']
,1
	['promoOpening' => '27/11/2022']
]

Then the sorting bit using usort:

function sortByDate($x, $y) {
    return (strtotime($x['promoOpening']) < strtotime($y['promoOpening']) ? -1 : 1);
}

usort($array, 'sortByDate');

However I seem to get odd results. I think I am potentially missing a layer of logic here, help appreciated.

Link to comment
Share on other sites

This is how the array is being built - maybe its the way I'm trying to access the data and need to give each array item a name?

$competitions = [];

array_push($competitions, [
	'promoOpening' => '05/09/2022'
	]);

array_push($competitions, [
	'promoOpening' => '25/09/2022'
	]);

function sortByDate($x, $y) {
    return strtotime($x['promoOpening']) - strtotime($y['promoOpening']);
}

usort($competitions, 'sortByDate');

 

Link to comment
Share on other sites

Don't worry sorted it:

$competitions = [];

array_push($competitions, [
	'promoOpening' => '05-09-2022'
	]);

array_push($competitions, [
	'promoOpening' => '25-09-2022'
	]);

function sortByDate($a, $b) {
    $a = date("Y-m-d", strtotime($a['promoOpening']));
    $b = date("Y-m-d", strtotime($b['promoOpening']));

    return ($a < $b) ? 1 : -1;
}

usort($competitions, 'sortByDate');

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...