dongou2019 2016-09-20 08:51
浏览 43
已采纳

PHP - 按SubArray值排序数组通过维护原始Array键

I would like to Sort an Array with its sub array value ("Name") but keeping its original array key.

default Array:

Array (
    [251] => Array
        (
            [color] => 
            [name] => 8
            [nbr] => 1
            [url_name] => taille-8
            [meta_title] => 
        )

    [323] => Array
        (
            [color] => 
            [name] => 7
            [nbr] => 2
            [url_name] => taille-7
            [meta_title] => 
        )

    [127] => Array
        (
            [color] => 
            [name] => 34
            [nbr] => 2
            [url_name] => taille-34
            [meta_title] => 
        )
);

By using array_multisort, I can able to get following Array:

Array(
    [0] => Array
        (
            [color] => 
            [name] => 7
            [nbr] => 2
            [url_name] => taille-7
            [meta_title] => 
        )

    [1] => Array
        (
            [color] => 
            [name] => 8
            [nbr] => 1
            [url_name] => taille-8
            [meta_title] => 
        )

    [2] => Array
        (
            [color] => 
            [name] => 34
            [nbr] => 2
            [url_name] => taille-34
            [meta_title] => 
        )
);

But what i need is,

Array(
    [323] => Array
        (
            [color] => 
            [name] => 7
            [nbr] => 2
            [url_name] => taille-7
            [meta_title] => 
        )

    [251] => Array
        (
            [color] => 
            [name] => 8
            [nbr] => 1
            [url_name] => taille-8
            [meta_title] => 
        )

    [127] => Array
        (
            [color] => 
            [name] => 34
            [nbr] => 2
            [url_name] => taille-34
            [meta_title] => 
        )
);

Thanks in adv :)

  • 写回答

4条回答 默认 最新

  • doujiaochan7317 2016-09-20 09:14
    关注

    $arr being your array:

    //obtain list of values to sort by
    foreach ($arr as $id => $value) {
        $names[$id] = $value['name'];
    }
    $keys = array_keys($arr);
    array_multisort(
        $names, SORT_ASC, SORT_NUMERIC, $arr, $keys
    );
    $result = array_combine($keys, $arr);
    

    You were probably missing the last step combining the array with given keys.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?