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];
}
\$\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.

\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.