ndAR ndAR - 2 days ago 3
PHP Question

Sort multidimensional array by key of set of array

I'm looking for a solution to sort by key a multi dimensional array, the point is that I can sort a set of array with multidimensional that has no custom key ID and the array is in set, but this array contains custom key and I need to sort by date:

My array is:

$newDataSet = array(
'2017-02-03' => array(
array(
array(
'name' => 'Paul',
'state' => 'in',
'date' => '2017-02-03'
),
array(
'name' => 'Paul',
'state' => 'out',
'date' => '2017-02-03'
)
)
),
'2017-01-02' => array(
array(
array(
'name' => 'John',
'state' => 'in',
'date' => '2017-01-02'
),
array(
'name' => 'John',
'state' => 'out',
'date' => '2017-01-02'
)
)
),
'2017-04-01' => array(
array(
array(
'name' => 'Smith',
'state' => 'in',
'date' => '2017-04-01'
),
array(
'name' => 'Smith',
'state' => 'out',
'date' => '2017-04-01'
)
)
)
);

uasort($newDataSet, function($a, $b) { return($a['date'] - $b['date']); });


As I understand usort will sort only the array of the multidimensional, so in my case is wrong because I don't have the structure to use it, is there a way to order by key asc ? I mean by
date
asc ?

Any hint/documentation for better understanding is appreciated.

Expected result:

$newDataSet = array(
'2017-01-02' => array(
array(
array(
'name' => 'Paul',
'state' => 'in',
'date' => '2017-01-02'
),
array(
'name' => 'Paul',
'state' => 'out',
'date' => '2017-01-02'
)
)
),
'2017-02-03' => array(
array(
array(
'name' => 'John',
'state' => 'in',
'date' => '2017-02-03'
),
array(
'name' => 'John',
'state' => 'out',
'date' => '2017-02-03'
)
)
),
'2017-04-01' => array(
array(
array(
'name' => 'Smith',
'state' => 'in',
'date' => '2017-04-01'
),
array(
'name' => 'Smith',
'state' => 'out',
'date' => '2017-04-01'
)
)
)
);

Answer

you can use ksort(), live demo.

ksort($newDataSet);
print_r($newDataSet);