doulaozhi6835 2013-02-12 11:12
浏览 101
已采纳

使用array_merge_recursive合并2个数组不能正常工作

My database has 2 columns. the person's ID is repeated 5 times in 1 column and each its paired in another column with a question answer Something like this:

ID  Answer
1   A1
1   A4
1   A2
1   A9
1   A3
12  A1
12  A11
12  A12
12  A17
12  A2

What i want to try to do is to merge all the answers into 1 array with its ID something like

array (
        [1] => array ( 0 => 'A1', 1 => 'A4', 2 => 'A2', 3 => 'A9', 4 => 'A3'),
        [12] => array ( 0 => 'A1', 1 => 'A11', 2 => 'A12', 3 => 'A17', 4 => 'A2')
        )

My code is as follows:

foreach ($quiz_answers as $aq => $aa)
            {
                $array_loop = array(  $aa['response_id'] => array( $aa['answer'] ) );
                $ss = array_merge_recursive($array_loop, $array_loop);

            }

My Problem is that somehow the loop doesnt merge in the desired way and i only get 2 outputs. I am not very good at manipulating arrays and probably i need another function but i am not quite sure what i am missing. I've tried using another variable in array_merge_recursive($anotherVariable, $array_loop); but this doesnt work either.

  • 写回答

4条回答 默认 最新

  • doudao8283 2013-02-12 11:26
    关注

    Simply change your foreach loop to construct the resulting array how you desire.

    foreach ($quiz_answers as $aa) {
        $ss[$aa['response_id']][] = $aa['answer'];
    }
    

    This gives an $ss array as you want:

    array(
        1  => array('A1', 'A4', 'A2', 'A9', 'A3'),
        12 => array('A1', 'A11', 'A12', 'A17', 'A2'),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料