PHP - replace values of array with another array

后端 未结 5 1307
别那么骄傲
别那么骄傲 2021-01-19 14:56

Is there a way i can replace the values of one array with the values of another which has identical keys?

$arr1 = Array
        (
            [key1] => va         


        
相关标签:
5条回答
  • 2021-01-19 15:11

    If the keys in array 1 and 2 are identical:

    $arr1 = $arr2;
    

    If all keys of array 2 are guaranteed to be in array 1 (array 2 is a subset of array 1):

    $arr1 = array_merge($arr1, $arr2);
    

    If some keys of array 2 are not in array 1 and you want only the keys that are in array 1 to be replaced (array 2 is not a subset of array 1, and you only want to merge the intersecting part):

    $arr1 = array_merge($arr1, array_intersect_key($arr2, $arr1));
    
    0 讨论(0)
  • 2021-01-19 15:11

    If you need to preserve an order of the array, use array_replace:

        $a = array( 'a' => 1, 'b' => 2,  'c' => 3  );
        $b = array(           'b' => 20, 'c' => 30 );
    
        $r = array_replace($a, $b)
    
        // $r = array( 'a' => 1, 'b' => 20, 'c' => 30 );
    
    0 讨论(0)
  • 2021-01-19 15:19

    Simply use the replace function.

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

    or better of if you want to deal with multi-dimensional array, use recursive replace.

    $arr1 = array_replace_recursive($arr1, $arr2);
    

    For details check these links array_replace(), array_replace_recursive()

    0 讨论(0)
  • 2021-01-19 15:23

    Check php's array_merge() function.

    $arr1 = array_merge($arr1,$arr2);
    
    0 讨论(0)
  • 2021-01-19 15:30

    Editing Notes: This answer previously suggested using array_combine as a way of doing this. However, as several people have pointed out, that's not the correct way of solving this problem. This answer has been edited to be more relevant to actually solving the problem.


    To replace the values of one array with the values of another array you can use the PHP array_replace method. This assumes associative arrays with identical keys.

    The PHP documentation explains array_replace like this:

    array_replace() replaces the values of array1 with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.


    Also, this post: https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/ includes a handy graphic which helps to explain the difference between array_merge, array_replace, and the array union operator (+). Give the post the read if you desire, I've included the image below for reference:

    0 讨论(0)
提交回复
热议问题