0

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];
}
3

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

I missed an information. I want to map only if the person and data $key match each other. The basic code (hard coding) is looks like this: foreach ($person as $pkey => $pvalue) { foreach ($data as $dkey => $dval) { if($dkey == $pkey) { $person[$pkey]["tel"] = $adat[$dkey]; } } }

Your Answer

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.