Reputation: 1678
I've got an multidimensional array like this:
Array
(
[thursday] => Array
(
[0] => Array
(
[title] => Movie2
[time] => 15.30
[venue] => VenueA
)
[1] => Array
(
[title] => Movie1
[time] => 13.00
[venue] => VenueB
)
)
)
I want to sort it by time using array_multisort and this is going fine when I use it like this:
foreach ($movies['thursday'] as $key => $row) {
$time[$key] = $row['time'];
}
array_multisort($time, SORT_ASC, $movies['thursday']);
unset($time);
But in this way, I have to repeat this code for each day of the week. So I'd like to use:
foreach ($movies as $movie) {
foreach ($movie as $key => $row) {
$time[$key] = $row['time'];
}
array_multisort($time, SORT_ASC, $movie);
unset($time);
}
But now the array remains unsorted. As far as I can see the latter piece of code is functional equal to the former piece of code. Or am I making a huge conceptual mistake?
Upvotes: 0
Views: 2206
Reputation: 1678
Found out the answer, using while
does the trick.
while($elements = each($movies)) {
foreach($movies[$elements['key']] as $key => $row) {
$time[$key] = $row['time'];
}
array_multisort($time, SORT_ASC, $movies[$elements['key']]);
unset($time);
}
Upvotes: 1
Reputation: 61
Are you running PHP4 or 5? In 4, a foreach loop doesn't create a reference like it does in 5. That could be why your second code sample isn't working. If that's the case you could convert it to be a for loop...
for ($i = 0; $i < count($movies); $i++) {
foreach ($movies[$i] as $key => $row) {
$time[$key] = $row['time'];
}
array_multisort($time, SORT_ASC, $movies[$i]);
unset($time);
}
Upvotes: 2
Reputation: 2633
I ran across a similar issue. Apparently some older versions of array_multisort don't work correctly with mixed values. I was digging about for the exact bug and version, but where I found it escapes me at the moment. I'll update this if I find it.
Upvotes: 0