views:

314

answers:

3

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?

A: 

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.

Bill
+2  A: 

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);
}
kdevine
Running PHP4, so that explains something. Your solution does not work though, because you cannot refer to an item in an assoc. array with a numerical index (e.g. array['value'] != array[0])
vjo
+1  A: 

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