【问题标题】:PHP : How to merge child arrays?PHP:如何合并子数组?
【发布时间】:2017-10-22 06:27:11
【问题描述】:

我有:

$colors = array(
    'apple' => array('green', 'red'),
    'grape' => array('green', 'purple'),
);

$countries = array(
    'apple' => array('china', 'usa')
    'grape' => array('spain', 'france')
);

预期输出:

$result = array(
    'apple' => array('green', 'red', 'china', 'usa'),
    'grape' => array('green', 'purple', 'spain', 'france'),
);

我怎样才能做到这一点?

【问题讨论】:

  • array_merge_recursive($colors,$countries) 一定够用
  • 您在国家/地区数组中缺少逗号...

标签: php arrays loops


【解决方案1】:
$result = array_merge_recursive($colors, $countries);

阅读更多:http://php.net/manual/en/function.array-merge-recursive.php

【讨论】:

    【解决方案2】:

    希望这个最简单的方法会有所帮助。

    Try this code snippet here

    <?php
    
    $colors = array(
        'apple' => array('green', 'red'),
        'grape' => array('green', 'purple'),
    );
    
    $countries = array(
        'apple' => array('china', 'usa'),
        'grape' => array('spain', 'france')
    );
    foreach($colors as $key => &$value)
    {
        $value=array_merge($value,$countries[$key]);
    }
    print_r($colors);
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2013-06-07
      相关资源
      最近更新 更多