2

I have an array like this

Array
(
    [bms] => Array
        (
            [0] => 123456_bms_for__on__(10-06-2015_18-57).pdf
        )

    [fr] => Array
        (
            [0] => 123456_fr_on_09-21-2015_(09-22-2015_11-46).pdf
        )

    [pcm] => Array
        (
            [0] => 123456_pcm_for_vignesh_on__(10-12-2015_12-30).pdf
        )

    [fds] => Array
        (
            [0] => 123456_fds_ext_for__on__(08-25-2015_10-23).pdf
        )

    [dr] => Array
        (
            [0] => 123456_dr_for__on___(10-23-2015_13-06).pdf
        )

)

And i want to order this array into (bms,dr,fds,pcm,fr) order

Array
(
    [bms] => Array
        (
            [0] => 123456_bms_for__on__(10-06-2015_18-57).pdf
        )
    [dr] => Array
        (
            [0] => 123456_dr_for__on___(10-23-2015_13-06).pdf
        )
    [fds] => Array
        (
            [0] => 123456_fds_ext_for__on__(08-25-2015_10-23).pdf
        )
    [pcm] => Array
        (
            [0] => 123456_pcm_for_vignesh_on__(10-12-2015_12-30).pdf
        )

    [fr] => Array
        (
            [0] => 123456_fr_on_09-21-2015_(09-22-2015_11-46).pdf
        )
)

Please help me to sort out array and help me to achieve the array in new order How to arrange array based on its key value

4
  • use ksort() to acheive Commented Oct 27, 2015 at 9:52
  • not in alphabetic order....it will arrange as per given array Commented Oct 27, 2015 at 9:53
  • if you have predefined above keys which will not increase in future you can think about reconstructing the array. Commented Oct 27, 2015 at 10:03
  • 1
    @ uchiha..... I want order (bms,dr,fds,pcm,fr) ... but result is (bms,dr,fds,fr,pcm) Commented Oct 27, 2015 at 10:07

2 Answers 2

2

You can use uksort like as

$pos = ['bms', 'dr', 'fds', 'pcm', 'fr'];
uksort($arr, function ($a, $b) use ($pos) {
    foreach ($pos as $value) {
        if ($value == $a) {
            return 0;
            break;
        }
        if ($value == $b) {
            return 1;
            break;
        }
    }
});

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

You can use uksort PHP function.

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

$sortOrder = array("bms", "dr", "fds", "pcm", "fr");

uksort($yourArray, function($a, $b) use ($sortOrder) {
    return array_search($a, $sortOrder) - array_search($b, $sortOrder); 
});

Working IDEOne or eval.in demos.

1 Comment

Even shorter now, without global :)

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.