0
\$\begingroup\$

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];
}
asked Nov 25, 2015 at 9:44
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Review. Please declare your cross-post \$\endgroup\$ Commented 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\$ Commented Oct 7, 2022 at 20:36

1 Answer 1

2
\$\begingroup\$

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.

answered Nov 25, 2015 at 12:56
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.