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条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集