Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array like this

Array
(
    [name] => Array
        (
            [0] => img/test240.jpg
            [1] => img/cs1.jpg
            [2] => img/cs2.jpg
            [3] => img/cs3.jpg
        )

    [link] => Array
        (
            [0] => http://google.com
            [1] => http://google.com
            [2] => http://facebook.com
            [3] => http://orkut.com
        )

    [order] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 2
            [3] => 3
        )

)

I need to sort it by order WHICH IS KEY in Multidimensional array. Here is output.

Array
(
    [name] => Array
        (
            [1] => img/cs1.jpg
            [2] => img/cs2.jpg
            [3] => img/cs3.jpg
            [0] => img/test240.jpg
        )

    [link] => Array
        (
            [1] => http://google.com
            [2] => http://facebook.com
            [3] => http://orkut.com
            [0] => http://google.com
        )

    [order] => Array
        (
            [1] => 1
            [2] => 2
            [3] => 3
            [0] => 4
        )

)

In this you can see when order is sorted name and link is also sorted according to the order. How can i do this with php.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to use array_map() in conjunction with sort().
If you want to preserve actual element order you have to use asort() instead sort().

Try this code:

$arr = array(
    'name' => array(
        0 => 'img/test240.jpg',
        1 => 'img/cs1.jpg',
        2 => 'img/cs2.jpg',
        3 => 'img/cs3.jpg',
    ),
    'link' => array(
        0 => 'http://google.com',
        1 => 'http://google.com',
        2 => 'http://facebook.com',
        3 => 'http://orkut.com',
    ),
    'order' => array(
        0 => 4,
        1 => 1,
        2 => 2,
        3 => 3,
    ),
);
function mysort($a) {
    asort($a);
    return $a;
}
$arr = array_map('mysort', $arr);
print_r($arr);

Demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...