【问题标题】:array_merge removes a empty stringarray_merge 删除一个空字符串
【发布时间】:2021-09-25 06:56:04
【问题描述】:

使用array_merge()时有一点不明白:

$defaultOptions = [
        'active' => null,
        'activeClass' => 'active',
        'wrapper' => [
            'attributes' => null,
            'templateVars' => null
        ],
        'item' => [
            'hasChildrenClass' => '', // this disappears after array_merge
            'attributes' => null,
            'linkAttrs' => null,
            'templateVars' => null
        ]
    ];

    $options = [
        'active' => [5,3],
        'item' => [
            'attributes' => ['class' => 'test']
        ]
    ];

$options = array_merge($defaultOptions, $options);

$options 的结果是

[
      'active' => [
        (int) 0 => (int) 5,
        (int) 1 => (int) 3,
      ],
      'activeClass' => 'active',
      'wrapper' => [
        'attributes' => null,
        'templateVars' => null,
      ],
      'item' => [
        'attributes' => [
          'class' => 'test',
        ],
      ],
    ]

我不明白为什么 $options['item']['hasChildrenClass'] 在我的结果中消失了?

【问题讨论】:

  • 您将初始$defaultOptions 中的整个item 替换为新$options 中给出的内容

标签: php arrays multidimensional-array array-merge


【解决方案1】:

array_merge() 中,如果数组具有相同的字符串键,则后面数组中的值将覆盖前面的数组。如果数组有数字键,那么后面数组中的值将附加上一个。 如果数组包含nullempty 值,则该值将被跳过并从合并数组中删除。

Read more at php.net manual

【讨论】:

  • 谢谢,但我还是有点困惑,为这种类型的数组合并选项的最佳方法是什么? array_replace_recursive ?
猜你喜欢
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2013-04-14
  • 2021-04-21
  • 1970-01-01
  • 2011-04-08
  • 2011-06-24
  • 2023-03-14
相关资源
最近更新 更多