【问题标题】:array_push with associative arrayarray_push 与关联数组
【发布时间】:2019-11-22 11:07:50
【问题描述】:

我有一个这样的数组:

 $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'] = $addimage['images'];

标签: php array-push


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    $allauto['images'] = [
                'src1' => 'xxxxx',
                'src2' => 'yyyyy'
             ];
    

    尝试使用 $allauto['images'] 这个而不是新变量

    【讨论】:

      【解决方案3】:

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

      <?php
      
      $alpha = [
          'name' => 'Adam',
          'type' => 'person',
      ];
      
      $beta = [
          'image' => 'man'
      ];
      
      $out = $alpha + $beta;
      
      var_export($out);
      

      输出:

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

      来自manual

      + 运算符返回附加到左侧的右侧数组 大批;对于两个数组中都存在的键,来自 将使用左侧数组,并且匹配元素来自 右侧数组将被忽略。

      【讨论】:

        猜你喜欢
        • 2012-01-07
        • 1970-01-01
        • 2011-08-13
        • 2012-01-21
        • 2011-09-06
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2014-06-21
        相关资源
        最近更新 更多