简体   繁体   中英

mapping associative array with another associative array

I found a way to solve my problem, but I want to see if there is any better or clear solution for this. I have two associative arrays like this:

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

I want to map the two arrays if their keys are equal. So the result should look like this:

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

My code:

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

Your method looks fine to me. For your example I'd do it like this:

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

Simply because when I come back to the code months down the line I can quickly see that I am iterating and changing an array from the use of array_walk - really is personal preference I think.

It look like that you want to loop two array with the same index ... so try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM