douhuibo5635 2017-03-03 23:01
浏览 111
已采纳

PHP - 用另一个不相同的数组替换数组的值

Is there a way i can replace the values of one array with the values of another non identical array and obtain as result only the first (updated) array? For example:

$arr1 = Array
        (
            [key3] => var3
            [key4] => var4
        )
$arr2 = Array
        (
            [key1] => var1
            [key2] => var2
            [key3] => new_var
            [key4] => new_var
            [key5] => var5
            [key6] => var6
        )

I want to get:

$arr_result = Array
        (
            [key3] => new_var
            [key4] => new_var
        )

$arr_result = array_merge($arr1, $arr2)

is not the solution

  • 写回答

5条回答 默认 最新

  • dongliao8069 2017-03-04 00:00
    关注

    In order to achieve this, you can use array_replace along with array_keys_intersect:

    $result = array_intersect_key(array_replace($arr1, $arr2), $arr1);
    

    Here is working demo.

    However simply looping through the first array and replacing values yourself is more optimal in this case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部