phparraysmultidimensional-arrayreplace

Replace row data of a 2d array if a row with the same identifying column value is found in another 2d array


I have two arrays

$array_1 = array(
    array('name' => 'Jon', 'user' => 'Apple'),
    array('name' => 'Dave', 'user' => 'Windows')     
);
          
$array_2 = array(
    array('name' => 'Jon', 'user' => ''), 
    array('name' => 'Jonson', 'user' => ''), 
    array('name' => 'Dave', 'user' => '')
);

I need to get this:

$array_result = array(
    array('name' => 'Jon', 'user' => 'Apple'), 
    array('name' => 'Jonson', 'user' => ''), 
    array('name' => 'Dave', 'user' => 'Windows')
);

I have tried array_merge() and have tried to filter arrays array_filter() but can't find solution.


Solution

  • You can make your arrays associative with array_columns third argument then use array_replace_recursive to get the change you want.
    The optionally use array_values to get an indexed array again.

    $array_1 = array_column($array_1, Null, "name");
    $array_2 = array_column($array_2, Null, "name");
    
    
    $result = array_values(array_replace_recursive($array_2, $array_1));
    
    var_dump($result);
    

    Output:

    array(3) {
      [0]=>
      array(2) {
        ["name"]=>
        string(3) "Jon"
        ["user"]=>
        string(5) "Apple"
      }
      [1]=>
      array(2) {
        ["name"]=>
        string(6) "Jonson"
        ["user"]=>
        string(0) ""
      }
      [2]=>
      array(2) {
        ["name"]=>
        string(4) "Dave"
        ["user"]=>
        string(7) "Windows"
      }
    }
    

    https://3v4l.org/EcgFh