Sorting an array without array_multisort
Posted: Mon Jan 25, 2010 4:05 pm
I am used to using array_multisort and a wonderous thing it is too, but I'm seeing a result I simply don't understand and somehow sorting my array without getting as far as array_multisort. So to explain...
I have a nested array so a number of nodes, each with a child array of a number of further nodes. One of these child nodes is a date (in yyyymmdd format), so something like:
And I want to sort in array by date order. Simple...
So what am I complaining about. Well this...
The result I cannot understand is that $sortByDate is $masterArray as if sorted by date through array_multisort, yet I would expect $sortByDate to simply be a clone of $masterArray built up by appending each $childArray defined during the foreach loop reproducing what I'd started with. A useless exercise...
So I am at a loss to see how I end up in the second example with a sorted array. There is no array indexing going on in the foreach loop that would result in the recordering of the array. Quite what am I doing? I cannot see how I am building a sorted array!
I have a nested array so a number of nodes, each with a child array of a number of further nodes. One of these child nodes is a date (in yyyymmdd format), so something like:
Code: Select all
Array
(
[0] => Array
(
[date] => 20100501
[value2] => South
[value3] => 7
)
[1] => Array
(
[date] => 20100424
[value2] => North
[value3] => 7
)
...Code: Select all
foreach($masterArray as $childArray)
{
$sortByDate[] = $childArray['date'];
}
$success = array_multisort($sortByDate, SORT_ASC, $masterArray);
print_r($masterArray);Code: Select all
foreach($masterArray as $childArray)
{
$sortByDate[] = $childArray;
}
print_r($sortByDate);So I am at a loss to see how I end up in the second example with a sorted array. There is no array indexing going on in the foreach loop that would result in the recordering of the array. Quite what am I doing? I cannot see how I am building a sorted array!