duanchao1002 2015-12-20 09:09
浏览 53
已采纳

多维数组按另一个数组值排序

I'm trying to sort out the sequence of individual array. How to use my another array list?

There is a predefined array:

$sortOrder = array("Night","Breakfast","Lunch","Dinner","Lying");

And this is it my original array content:

Array
(
    [Normal] => Array
        (
        [Dinner] => Array
            (
                [avgtime] => 17,06
                [avg] => 5.24
            )

        [Breakfast] => Array
            (
                [avgtime] => 04,25
                [avg] => 4.96
            )

        [Lying] => Array
            (
                [avgtime] => 14,49
                [avg] => 4.7
            )

        [Lunch] => Array
            (
                [avgtime] => 09,53
                [avg] => 5.26
            )

        [Night] => Array
            (
                [avgtime] => 00,00
                [avg] => 4.4
            )

    )

[High] => Array
    (
        [Dinner] => Array
            (
                [avg] => 9
                [avgtime] => 17,35
            )

    )

[Low] => Array
    (
        [Night] => Array
            (
                [avg] => 3.5
                [avgtime] => 02,35
            )

        [Breakfast] => Array
            (
                [avg] => 3.8
                [avgtime] => 07,12
            )
    )
)

How can I order placed based on the list? Please help me, and thanks so much!

  • 写回答

2条回答 默认 最新

  • du42561 2015-12-20 10:09
    关注

    To achieve more efficient key searching let's use static arrays in the comparison function:

    foreach ($arr as $key => $row) {
      uksort($arr[$key], function($a, $b) {
        static $sortOrder = ['Night', 'Breakfast', 'Lunch', 'Dinner', 'Lying'];
    
        static $order;
        if (!isset($order)) {
          $order = array_flip($sortOrder);
        }
    
        $value = 0;
        if (array_key_exists($a, $order) && array_key_exists($b, $order)) {
          $value = ($order[$a] > $order[$b] ? 1 : -1);
        }
        return $value;
      });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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