普通网友 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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?