dongshanyan0322 2014-01-19 03:05
浏览 94
已采纳

将数组添加到数组数组中

Ideally, I'd like the ability to add a 3rd array into an array of 2 arrays. I've tried array_push, array_merge, and array_merge_recursive. Here is the relevant code:

$array1 = array("color" => "red", "shape" => "triangle");
$array2 = array("color" => "green", "shape" => "trapezoid");
$array3 = array("color" => "blue", "shape" => "square");
$result = array($array1, $array2);
$result = array_merge($result, $array3);
print_r($result); 

This current code returns: Array ( [0] => Array ( [color] => red [shape] => triangle ) [1] => Array ( [color] => green [shape] => trapezoid ) [color] => blue [shape] => square )

The problem with it is I need it to number the 3rd array as well. So, [0], [1], and [2]

  • 写回答

2条回答 默认 最新

  • dro60731 2014-01-19 03:14
    关注
    $array1 = array("color" => "red", "shape" => "triangle");
    $array2 = array("color" => "green", "shape" => "trapezoid");
    $array3 = array("color" => "blue", "shape" => "square");
    
    $result = array($array1, $array2);
    
    array_push($result, $array3);
    

    array_push is the way to go because you will add the new array to the array of arrays. The issue with array_merge is that it takes the contents of $array3 (not the array itself) and adds them to $result.

    When you said that you previously tried array_push I'm guessing that you used it incorrectly like this: $result = array_push($result, $array3); which will overwrite the result you're looking for with the length of the created array, rather than the array you're creating.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大