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

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决