0

I am trying to merge arrays with the same keys with different values, like below.

Input:

$array1 = array('1933' => array(
    'nid' => '492811',
    'title' => 'NEW TITLE',
    'field_link_single_url' => 'abc',
    'field_link_single_title' => 'test' 
    ));
    
$array2 = array('1933' => array(
    'nid' => '492811',
    'title' => 'NEW TITLE',
    'field_link_single_url' => 'xyz',
    'field_link_single_title' => 'abcd' 
    ));

Expected output to be:

Array
(
    [nid] => 492811
    [title] => NEW TITLE
    [field_link_single_url] => [
          [0] => 'abc',
          [1] => 'xyz'
    ]
    [field_link_single_title] => [
          [0] => 'test',
          [1] => 'abcd'
    ]
)

I have tried array_merge and array_merge_recursive but it does not work as expected.

Output of array_merge_recursive($array1[1933], $array2[1933]) it is creating duplicates keys having same value

Array
(
    [nid] => Array
        (
            [0] => 492811
            [1] => 492811
        )

    [title] => Array
        (
            [0] => Hal  Louchheim
            [1] => Hal  Louchheim
        )

    [field_link_single_url] => Array
        (
            [0] => abc
            [1] => xyz
        )

    [field_link_single_title] => Array
        (
            [0] => test
            [1] => abcd
        )

)
10
  • Is that a typo? array_merge_recursive should do what you need Commented Aug 19, 2020 at 14:45
  • 1
    @AndyHolmes No...? 3v4l.org/FSV7Y Commented Aug 19, 2020 at 14:49
  • array_merge_recursive can't turn string into array. Commented Aug 19, 2020 at 14:49
  • It is possible to use array_merge_recursive if you would leave first level of tree (with key "1933"). As long as you need to keep this structure there is not native one-line function and you have to write your own function and iterate it by your own. Commented Aug 19, 2020 at 14:50
  • 1
    What have you tried ? Commented Aug 19, 2020 at 14:51

1 Answer 1

2

I made some assumption. If these assumptions are not valid, you should add some additional checks:

  • Both $array1 and $array2 are really arrays
  • Both $array1 and $array2 have the exact same keys
  • The values inside $array1 and $array2 are primitive types, not complex objects (the === operator would not work to compare objects or arrays)
function mergeArrayValues($array1, $array2) {
  $output = [];
  foreach($array1 as $key => $value) {
    $output[$key] = $array1[$key] === $array2[$key] 
       ? $array1[$key]
       : [ $array1[$key], $array2[$key] ]
  }
  return $output;
}

mergeArrayValues($array1[1933], $array2[1933])

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

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.