Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

Sort php different format multidimensional array on key

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...