带有关联数组的array_push

问题描述 投票:-2回答:3

我有一个像这样的数组:

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

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

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

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

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

我用array_push尝试了不同的事情,但是我在两个数组之间得到了像0和1这样的键...谁能帮忙?

php array-push
3个回答
0
投票
$allauto['images'] = [
            'src1' => 'xxxxx',
            'src2' => 'yyyyy'
         ];

尝试使用$ allauto ['images']代替新变量


2
投票

首先,您应该检查所有缺少的花括号和意外的逗号。但是,如果您正在寻找问题的答案,则可以使用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"
    }
}

0
投票

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

<?php

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

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

$out = $alpha + $beta;

var_export($out);

输出:

array (
    'name' => 'Adam',
    'type' => 'person',
    'image' => 'man',
  )
© www.soinside.com 2019 - 2024. All rights reserved.