-1

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.

2 Answers 2

2

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

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

Comments

0

Most simply, create an associative lookup array for fast referencing later. Then iterate the second array and conditionally overwrite rows if they are found in the lookup. Demo

$replacement = array_column($array_1, null, 'name');
var_export(
    array_map(
        fn($row) => $replacement[$row['name']] ?? $row,
        $array_2
    )
);

Output:

array (
  0 => 
  array (
    'name' => 'Jon',
    'user' => 'Apple',
  ),
  1 => 
  array (
    'name' => 'Jonson',
    'user' => '',
  ),
  2 => 
  array (
    'name' => 'Dave',
    'user' => 'Windows',
  ),
)

Comments

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.