将关联数组映射到另一个关联数组

时间:2015-11-25 09:08:55

标签: php arrays dictionary associative-array

我找到了解决问题的方法,但我想知道是否有更好或更明确的解决方案。我有两个这样的关联数组:

$person= [
    "A" => [
            "sur" => "a",
            "fir" => "andras"
            ],
    "C" =>  [
            "sur" => "b",
            "fir" => "balint"
            ]
];
$data = [
    "A" => ["011", "012", "013"],
    "C" => ["021", "022"]
];

如果两个数组的键相等,我想映射它们。所以结果应该是这样的:

$person= [
    "A" => [
            "sur" => "a",
            "fir" => "andras",
            "tel" => ["011", "012", "013"]
            ],
    "C" =>  [
            "sur" => "b",
            "fir" => "balint",
            "tel" => ["021", "022"]
            ]
];

我的代码:

foreach ( array_intersect_key(array_keys($data,$person)) as $id) {
    $person[$id]['tel'] = $data[$id];
}

2 个答案:

答案 0 :(得分:1)

你的方法对我来说很好。对于你的例子我会这样做:

array_walk($person, function(&$v, $k) use ($data) {
    $v['tel'] = $data[$k];
});

仅仅因为当我回到代码的几个月后,我可以很快看到我正在迭代并使用array_walk更改数组 - 我认为这是个人偏好。

答案 1 :(得分:0)

看起来你想用相同的索引循环两个数组...... 所以试试这个

foreach ($person as $key => $value) {   
    $person[$key]['tel'] = $data[$key];         
}
var_dump($person);