普通网友 2016-11-28 13:51
浏览 37
已采纳

如何在php中复合一维数组和二维数组[重复]

This question already has an answer here:

I have two array one is two dimensional and second is one dimensional and want to merge in a two dimensional array.

For Example :

# array1
Array
(
    [0] => Array
        (
            [id] => 598          
        )

    [1] => Array
        (
            [id] => 599        
        )
)
# array2
Array
(       
    [id] => 66    
)

#resultant array
Array
(
    [0] => Array
        (
            [id] => 598
        )
    [1] => Array
        (
            [id] => 599
        )
    [2] => Array
        (
            [id] => 66         
        )
)

In above example array1 and array2 are two input array and want to result as resultant array.

I have tried array_merge php function but it is not working.

How to do that?

</div>
  • 写回答

2条回答 默认 最新

  • dow56114 2016-11-28 13:52
    关注

    If you just want to add an element it will work:

    $array1[] = $array2;
    

    If you want to create a new array it should work:

    <?php
    $array1 = [
        0 => ['id' => 598],
        1 => ['id' => 599],
    ];    
    $result_array = $array1;    
    $array2 = [
        'id' => 66,
    ];
    
    $result_array[] = $array2;    
    print_r($result_array);    
    ?>
    

    In this case just add to new element in $array1 an $array2.

    If you have more items in $array2 you can do it like follows:

    $result_array = $array1; 
    foreach ($array2 as $key => $value) {
        $result_array[] = [$key => $value];
    }
    print_r($result_array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题