dregduc63699 2012-04-27 08:03
浏览 37
已采纳

PHP排序按重量排序的多维数组

I just asked this question a moment ago but I asked incorrectly so I apologize.

I'm hoping there's an easy way to do this without tons and tons of loops.

I have a matrix in the following manner:

      Foo1    Foo2    Foo3 ....   FooN
Jan    1       8       5            4
Feb    10      12      15          11
Mar    12      7       4            3
Apr    10      16      7           17

Assuming the following array:

$arrayMonths = array(
       'jan' => array(1, 8, 5,4)
       'feb' => array(10,12,15,11)
       'mar' => array(12, 7, 4, 3)
       'apr' => array(10,16,7,17)
    );

I need to sort the above array and show it in the following manner:

array[apr][FooN] = 17
array[feb][Foo3] = 15
array[mar][Foo1] = 12
array[jan][Foo2] = 8

Essentially, I need to get the greatest sum of the above weights, one month can only have one foo and one foo can only have one month. In the above example, the result would be 52.

Thanks

  • 写回答

5条回答 默认 最新

  • dongle7553 2012-04-27 08:18
    关注

    See Demo : http://codepad.org/vDI2k4n6

    $arrayMonths = array(
           'jan' => array(1, 8, 5,4),
           'feb' => array(10,12,15,11),
           'mar' => array(12, 7, 4, 3),
           'apr' => array(10,16,7,17),
        );
    
    $position = array("Foo1","Foo2","Foo3","FooN");
    $set = array();
    
    foreach($arrayMonths as $key => $value)
    {
        $max = max($value);
        $pos = array_search($max, $value);
        $set[$key][$position[$pos]] = $max ;
    }
    
    
    function cmp($a, $b)
    {
        foreach($a as $key => $value )
        {
            foreach ($b  as $bKey => $bValue)
            {
                return $bValue - $value ;
            }
        }
    
    }
    
    uasort($set,"cmp");
    var_dump($set);
    

    Output

        array
          'apr' => 
            array
              'FooN' => int 17
          'feb' => 
            array
              'Foo3' => int 15
          'mar' => 
            array
              'Foo1' => int 12
          'jan' => 
            array
              'Foo2' => int 8
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制