You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多维数组合并:如何将国家与首都子数组合并为结构化数组

Solution to Merge Country and Capital Arrays

Absolutely! You can achieve the desired structure by pairing elements from the country and capital arrays by their index, then building the new countries subarray. Here's how to do it:

Step-by-Step Code Example

First, let's define your original array for clarity:

$arr = [
    'country' => ['France', 'Canada'],
    'capital' => ['Paris', 'Ottawa'],
    'other' => 'value'
];

Now, transform it to the desired format:

$result = [];

// Build the countries array by pairing country and capital elements
$result['countries'] = [];
foreach ($arr['country'] as $index => $countryName) {
    $result['countries'][] = [
        'country' => $countryName,
        'capital' => $arr['capital'][$index]
    ];
}

// Preserve the 'other' key from the original array
$result['other'] = $arr['other'];

Output

Running this code will give you exactly the structure you want:

Array (
    [countries] => Array (
        [0] => Array ( [country] => France [capital] => Paris )
        [1] => Array ( [country] => Canada [capital] => Ottawa )
    )
    [other] => value
)

Why Your Original Code Didn't Work

Your initial approach using array_merge() combines arrays by their keys (or numeric indices, which get reindexed), so merging ['France', 'Canada'] and ['Paris', 'Ottawa'] would just create a single flat array like ['France', 'Canada', 'Paris', 'Ottawa']—not the paired associative arrays you need. Instead, we iterate over each index to explicitly pair each country with its corresponding capital.

Note

This solution assumes the country and capital arrays are the same length. If there's a chance they might not be, you could add a check (like isset($arr['capital'][$index])) to avoid undefined index errors.

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:45:29