PHP: Sort multi-dimension array [closed]

邮差的信 提交于 2020-01-05 10:26:39

问题


I have multi-dimension array like:

Array
(
    [name] => Array
        (
            [0] => South Africa
            [1] => Australia
            [2] => Egypt
        )

    [img] => Array
        (
            [0] => sa-flag.jpg
            [2] => au-flag.jpg
            [1] => eg-flag.jpg
        )
)

and I want to sort it alphabetically such that its output will exactly like:

Array
(
    [name] => Array
        (
            [0] => Australia
            [1] => Egypt
            [2] => South Africa
        )

    [img] => Array
        (
            [0] => au-flag.jpg
            [2] => eg-flag.jpg
            [1] => sa-flag.jpg
        )
)

I could not be able to use sort on both keys to synchronize the country name with country flag.


回答1:


Please find below solution

$kd = array(
'name' => array(
        '0' => 'South Africa',
        '1' => 'Australia',
        '2' => 'Egypt',
    ),

'img' => array
    (
        '0' => 'sa-flag.jpg',
        '2' => 'au-flag.jpg',
        '1' => 'eg-flag.jpg',
    ),
);
array_multisort($kd['name'], SORT_ASC, SORT_STRING,$kd['img'], SORT_ASC, SORT_STRING);
echo '<pre>';
print_r($kd);

Find below core concept

http://www.php.net/manual/en/function.array-multisort.php#example-4840




回答2:


Try this

$arr = array_multisort($array);


来源:https://stackoverflow.com/questions/16209160/php-sort-multi-dimension-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!