peace_love
peace_love

Reputation: 6471

How can I merge an array into the child level of another array (recursively)?

array1:

array(1) {
  [0]=>
  array(2) {
    ["1234"]=>
    array(1) {
      ["fileName"]=>
      string(10) "monkey.jpg"
    }
    ["3456"]=>
    array(1) {
      ["fileName"]=>
      string(9) "horse.jpg"

    }
  }
}

array2:

array(2) {
  ["number"]=>
  string(2) "62"
  ["company"]=>
  string(7) "animals"
}

I want to merge the two arrays together:

$result = array_merge_recursive($array1,$array2);

This is the result:

array(3) {
  [0]=>
  array(2) {
    ["1234"]=>
        array(1) {
          ["fileName"]=>
          string(10) "monkey.jpg"
        }
     ["3456"]=>
        array(1) {
          ["fileName"]=>
          string(9) "horse.jpg"   
     }
  }
  ["number"]=>
  string(2) "62"
  ["company"]=>
  string(7) "animals"
}

But the result I would actually need is this:

array(1) {
  [0]=>
  array(4) {
     ["1234"]=>
          array(1) {
         ["fileName"]=>
          string(10) "monkey.jpg"
         }
      ["3456"]=>
         array(1) {
            ["fileName"]=>
           string(9) "horse.jpg"   
         }
      ["number"]=>
      string(2) "62"
      ["company"]=>
      string(7) "animals"
  }
}

How could I achieve this?


I test array_push like RaymondNijland suggested:

array_push($array1[0],$array2);

But now the $array1 looks like this:

array(1) {
  [0]=>
  array(3) {
    ["1234"]=>
     array(1) {
     ["fileName"]=>
      string(10) "monkey.jpg"
       }
    ["3456"]=>
       array(1) {
        ["fileName"]=>
        string(9) "horse.jpg"   
      }
    }
    [0]=>
    array(2) {
        ["number"]=>
         string(2) "62"
         ["company"]=>
         string(7) "animals"
    }
  }
}

Still not the result I am looking for

Upvotes: 0

Views: 68

Answers (2)

Sina Saderi
Sina Saderi

Reputation: 67

$array3 = $array1;
foreach ($array2 as $key => $value) {
  $array3[0][$key] = $value;
}

Upvotes: 1

Mike
Mike

Reputation: 181

Since you want to add to the existing array, iterate through the new array and add each element of it.

Here's the function and example usage:

function array_merge_recursive_custom($array1, $array2){
    $result[] = $array1;

    foreach($array2 as $key=>$value){
        $result[0][$key] = $value;
    }
    return $result;
}

$array1 = ['1234' => ['fileName' => 'monkey.jpg'], '3456' => ['fileName' => 'horse.jpg']];
$array2 = ['number' => '62', 'company' => 'animals'];

$result = array_merge_recursive_custom($array1, $array2);

var_dump($result);

Output:

array(1) {
  [0]=>
  array(4) {
    [1234]=>
    array(1) {
      ["fileName"]=>
      string(10) "monkey.jpg"
    }
    [3456]=>
    array(1) {
      ["fileName"]=>
      string(9) "horse.jpg"
    }
    ["number"]=>
    string(2) "62"
    ["company"]=>
    string(7) "animals"
  }
}

Upvotes: 1

Related Questions