phparrayssortingmultidimensional-arrayarray-multisort

Synchronously sort the rows of a 2d array


I have wrote a script to produce an array of data but now want to display in order of score. The array outputs as follows;

[display_name] => Array
    (
        [0] => ACT_Web_Designs
        [1] => user1_design
        [2] => user2_design
    )

[proffesion] => Array
    (
        [0] => Web Developer
        [1] => web developer
        [2] => Web Developer
    )

[score] => Array
    (
        [0] => 15
        [1] => 6
        [2] => 15
    )

[img] => Array
    (
        [0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
        [1] => 
        [2] => 
    )

so in a nutshell I am wanting it to be converted as follows;

    [display_name] => Array
    (
        [0] => ACT_Web_Designs
        [1] => user2_design
        [2] => user1_design
    )

[proffesion] => Array
    (
        [0] => Web Developer
        [1] => web developer
        [2] => Web Developer
    )

[score] => Array
    (
        [0] => 15
        [1] => 15
        [2] => 6
    )

[img] => Array
    (
        [0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
        [1] => 
        [2] => 
    )

I have been looking at asort() but cant get anything to work. any help would be much appreciated.


Solution

  • This is exactly where the PHP's array_multisort comes to use. It is a case where you want to sort many arrays based on the comparison happening in just one of them.

    I've modified the array score to have distinct values.

    <?php
    
    $arr = array(
                    'display_name' => array('ACT_Web_Designs','user1_design','user2_design'),
                    'proffesion' => array('Web Developer','web developer','web developer'),
                    'score' => array(12,6,15),
                    'img' => array('./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic','','')
                );
    
    var_dump($arr);
    array_multisort($arr['score'], SORT_ASC, SORT_NUMERIC,
                    $arr['display_name'],
                    $arr['proffesion'],
                    $arr['img']
                    );
    var_dump($arr);
    
    
    ?>
    

    Here goes a working demo.