0

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?

3 Answers 3

2

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);
}
1
  • 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]) Commented Jan 5, 2010 at 14:49
1

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.