dongpo1599 2009-12-12 16:45
浏览 103
已采纳

PHP中嵌套多维数组的多维数组

I have an array like so:

   sid         sname               did               dname
    1         Basketball            1                 Mini
    1         Basketball            3                 Cadet
    2         Baseball              8             Little League
    2         Baseball              6             Junior League
    1         Basketball            5                Masters

I was trying to get this and transform it to a nested array like so:

 array('Basketball' => array(
                        'id' => 1, 
                        'divisions' => array(
                                          1 => 'Mini',
                                          3 => 'Cadet',
                                          5 => 'Masters'
                                       )
                       ),
       'Baseball' => array(
                        'id' => 2, 
                        'divisions' => array(
                                          8 => 'Little League',
                                          6 => 'Junior League'
                                       )
                       )
 );

And I am using this foreach loop which is not working, it replaces each division entry so I'm left with only one division entry which is the last entry.

$result = '';
foreach($row as $r) 
{

     $result[$r['sname']] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname']));

}

This foreach loop gives me this result:

 array('Basketball' => array(
                        'id' => 1, 
                        'divisions' => array(
                                          5 => 'Masters'
                                       )
                       ),
       'Baseball' => array(
                        'id' => 2, 
                        'divisions' => array(
                                          6 => 'Junior League'
                                       )
                       )
 );

I don't understand what is wrong here.. can anybody help me out here?

  • 写回答

5条回答 默认 最新

  • douxu5233 2009-12-12 16:54
    关注

    The problem is that you redefine $result[$r['sname']] each time. You only need to define it if it is not already defined.

    $result = array(); // initialize this to an appropriate type!
    foreach($row as $r) 
    {
    
       if(!isset($result[$r['sname']]))
       {
          $result[$r['sname']] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname']));
          continue;
       }
       $result[$r['sname']]['divisions'][$r['did']] = $r['dname'];
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器