array_push 与关联数组

array_push with associative array

我有一个这样的数组:

 $allauto = [
        'name' => $title,
        'type' => 'simple',
        'description' => $description,
        'attributes' => [
           [
               'id' => 1,
               'visible' => true,
               'options' => $model,
           ],

我有一个像这样的数组 $addimage:

$addimage = [
           'images' [
                'src' => xxxxx
                'src' => yyyyy
                 ],
             ]

我如何将它们结合起来(与 array_push)?所以我得到这样的结果:

$allauto = [
            'name' => $title,
            'type' => 'simple',
            'description' => $description,
            'attributes' => [
               [
                   'id' => 1,
                   'visible' => true,
                   'options' => $model,
               ],
            'images' => [
               [
                    'src' => xxxxx
                    'src' => yyyyyy
               ]

我用 array_push 尝试了不同的方法,但我在 2 个数组之间得到了 0 和 1 这样的键... 有人可以帮忙吗?

$allauto['images'] = [
            'src1' => 'xxxxx',
            'src2' => 'yyyyy'
         ];

试试用 $allauto['images'] 这个代替新变量

首先,您应该检查所有缺少的大括号和意外的逗号。但是,如果您要寻找问题的答案,可以使用 array_merge 合并这两个数组。

固定版本:

$allauto = [
    'name' => $title,
    'type' => 'simple',
    'description' => $description,
    'attributes' => [
       [
           'id' => 1,
           'visible' => true,
           'options' => $model
       ]
    ]
 ];
$addimage = [
       'images' => [
            'src' => "yyyyy"
             ]
         ];

var_dump(array_merge($allauto, $addimage));

//Output:
array(5) {
    ["name"]=> string(3) "SDS"
    ["type"]=> string(6) "simple"
    ["description"]=>string(2) "SD"
    ["attributes"]=>array(1) {
                    [0]=> array(3) {
                            ["id"]=> int(1)
                            ["visible"]=> bool(true)
                            ["options"]=> string(4) "SDFF"
                        }
        }
    ["images"]=> array(1) {
                ["src"]=> string(5) "yyyyy"
    }
}

如果您有关联数组,只需使用 + 运算符:

<?php

$alpha = [
    'name' => 'Adam',
    'type' => 'person',
];

$beta = [
    'image' => 'man'
];

$out = $alpha + $beta;

var_export($out);

输出:

array (
    'name' => 'Adam',
    'type' => 'person',
    'image' => 'man',
  )

来自manual

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.