将数组添加到数组数组中

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]

$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.

You're merging an array of strings ($array3) with an array of arrays ($result).

To achieve the result you want, you should either do

$result = array($array1, $array2, $array3);

or use array_push() instead of array_merge()

$result = array($array1, $array2);
array_push($result, $array3);