在PHP中合并两个多维数组

时间:2019-05-30 12:14:00

标签: php arrays

假设我有这个数组:

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

是否可以合并countrycapital数组?

所需的输出如下:

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

我尝试过的事情:

$result = array();

foreach($arr as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}

3 个答案:

答案 0 :(得分:1)

如果countries-> capitals的键和长度相同,并且只需要合并这些值,则可以简单地在一个数组中递增。例如:

$result = ['countries' => [], 'other' => $arr['other']];
for ($i = 0; $i < count($arr['country']); $i++) {
    $result['countries'][] = [
        'country' => $arr['country'][$i],
        'capital' => $arr['capital'][$i]
    ];
}

答案 1 :(得分:1)

如果您知道要修改的字段,请使用:

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

foreach($arr as $k => $v) {
    if (in_array($k, $keys)) {
        $slice[] = $v; // get the array which need to be merge
        unset($arr[$k]); // remove him from the original array
    }
}

$arr["countries"] = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, array_map(null, ...$slice));

现在设置了$arr

请注意,使用...运算符将$slice数组和array_mapnull爆炸,它们根据int键组合在一起。

这是最通用的方法,因为如果您想更改字段以进行合并,则只需要在1个地方进行即可...

答案 2 :(得分:0)

尝试使用以下代码,它将100%有效

谢谢。

<?php

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


$result = [
    "countries"=>[]
];

for($i=0;$i<count($arr["country"]);$i++){
    $data = [
        "country"=>$arr["country"][$i],
        "capital"=>$arr["capital"][$i]
    ];
    array_push($result["countries"],$data);
}


echo "<pre>";
print_r($result);
echo "</pre>";