根据相同的键

时间:2018-05-26 03:29:13

标签: php arrays merge

我有这样的数组1

Array
(
    [0] => 1
    [1] => 2
)

第二个数组将是

Array
(
    [0] => Array
        (
            [FullName] => Bhupat Chippa
        )

    [1] => Array
        (
            [FullName] => Dvs Patel
        )
)

我想合并它的方式是将值添加到具有相同键的第二个数组。期望的输出将看起来像这样或某种方式,以便我可以使用数组1的值与仅第二阵列:

Array
(
    [0] => Array
        (
            [FullName] => Bhupat Chippa
            [0] => 1
        )

    [1] => Array
        (
            [FullName] => Dvs Patel
            [1] => 2
        )

)

2 个答案:

答案 0 :(得分:1)

您可以应用简单的foreach()来执行此操作

$final = [];

foreach($array2 as $key =>$arr2 ){
  $final[$key]['FullName'] = $arr2['FullName'];
  $final[$key][$key] = $array1[$key];
}

print_r($final);

输出: - https://eval.in/1010437

答案 1 :(得分:0)

如果两个数组的长度相同,您可以使用array_map作为第二个参数传递array_keys

$array1 = ["1", "2"];
$array2 = [
    ["FullName" => "Bhupat Chippa"],
    ["FullName" => "Dvs Patel"]
];

$result = array_map(function($x, $y) use ($array1){
    $x[$y] = $array1[$y];
    return $x;
}, $array2, array_keys($array1));

print_r($result);

Demo

那会给你:

Array
(
    [0] => Array
        (
            [FullName] => Bhupat Chippa
            [0] => 1
        )

    [1] => Array
        (
            [FullName] => Dvs Patel
            [1] => 2
        )

)