1

How can I achieve the third array, merging Array1 and Array2? What's the best way to do that in PHP? Many thanks. Array2 has like index (key), the associative value of id in Array1.

Array1

Array
(
    [0] => Array
    (
        [id] => 56
        [grade] => 6.7
    )
    [1] => Array
    (
        [id] => 214
        [grade] => 3.2
    )
)

Array2

Array
(
    [56] => 2.4
    [214] => 5.8 
)

Result wanted

Array
(
    [0] => Array
    (
        [id] => 56
        [grade] => 2.4
    )
    [1] => Array
    (
        [id] => 214
        [grade] => 5.8
    )
)
1
  • Have you tried anything? One way would be to loop over Array1, check if the id value is a key/set in Array2, and if so replace the grade value Commented Nov 16, 2015 at 18:09

1 Answer 1

1
foreach($array1 as &$arrayItem) {
$arrayItem['grade'] = $array2[$arrayItem['id']]
}

Here you will have array 1 merged as you wished

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

3 Comments

note this will produce Undefined Error notices and set the value of $arrayItem['grade'] to NULL if $array2[$arrayItem['id']] is not set.
That is correct, so there would have to come isset checks.
"Symmetric Array Destructuring" version: 3v4l.org/TPV1s

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.