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];
}
-
\$\begingroup\$ Welcome to Code Review. Please declare your cross-post \$\endgroup\$200_success– 200_success2015年11月25日 15:34:18 +00:00Commented Nov 25, 2015 at 15:34
-
\$\begingroup\$ What is not clear about the sample data (on both SE sites) is that we don't know what the desired result should be when one array has a key that the other array doesn't have. Is person the master array or data? \$\endgroup\$mickmackusa– mickmackusa2022年10月07日 20:36:25 +00:00Commented Oct 7, 2022 at 20:36
1 Answer 1
As to save some lines of code and to use the appropriate functions that PHP provides then yes, this is a perfect solution.
On the other point of view on somebody who wants to quickly read through your code and know whats happening, then I would have suggested a nested loop.
For both cases, a comment above your loop would be very appreciated.