Jump to content

[Solved] Sorting multi-dimensional array while keeping associations


Sashi

Recommended Posts

I'm trying to sort out a multi-dimensional array, but I need to keep the associations intact and I'm not sure how to do this. I need to sort the multi-dimensional array by the values of the first array while keeping up the associations in the second array. Example: I need to take the following...

[code]Array
(
    [ID] => Array
        (
            [0] => 2
            [1] => 1
        )

    [NAME] => Array
        (
            [0] => Fullmetal Alchemist
            [1] => Megaman NT Warrior
        )

)[/code]

...and have it sorted like this:

[code]Array
(
    [ID] => Array
        (
            [0] => 1
            [1] => 2
        )

    [NAME] => Array
        (
            [0] => Megaman NT Warrior
            [1] => Fullmetal Alchemist
        )

)[/code]

If you need any other info, or if I just explained something badly here make sure to tell me! Oh yeah, and however I can do this needs to be able to sort the first array ascending. Thanks for your help ;D
Use array_multisort: http://us2.php.net/manual/en/function.array-multisort.php

In your example, this would do it:

array_multisort(
    $ar[ID], SORT_NUMERIC, SORT_ASC,
    $ar[NAME], SORT_STRING, SORT_ASC);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.