Array and Associative Array Merge

£可爱£侵袭症+ 提交于 2019-12-02 08:59:38

问题


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:


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

Here you will have array 1 merged as you wished



来源:https://stackoverflow.com/questions/33741689/array-and-associative-array-merge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!