Drmzindec
Drmzindec

Reputation: 814

Flatten multidimensional array children

I have an PHP multidimensional array like the below. I would like to merge another array into this array:

array(3) {
  [0]=>
  array(4) {
    ["id"]=> "1"
    ["register"]=> "Value 1"
    ["link"]=> "link 1"
    ["approval"]=> "yes"
  }
  [1]=>
  array(4) {
    ["id"]=> "2"
    ["register"]=> "Value 2"
    ["link"]=> "Value 2"
    ["approval"]=> "no"
  }
  [2]=>
  array(4) {
    ["id"]=> "3"
    ["register"]=> "Value 3"
    ["link"]=> "link 3"
    ["approval"]=> "pending"
  }
}

The array i would like to merge looks like the following:

array(4) {
["image"]=> "123.png"
["start"]=> "8 October"
["end"]=> "9 October"
["days"]=> "2 Days"
}

Each of the first array keys has an array as the above that needs to be merged into it which is unique.

I would like the array to look look as follow:

array(3) {
  [0]=>
  array(8) {
    ["id"]=> "1"
    ["register"]=> "Value 1"
    ["link"]=> "link 1"
    ["approval"]=> "yes"
    ["image"]=> "image1.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
  [1]=>
  array(8) {
    ["id"]=> "2"
    ["register"]=> "Value 2"
    ["link"]=> "Value 2"
    ["approval"]=> "no"
    ["image"]=> "image2.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
  [2]=>
  array(8) {
    ["id"]=> "3"
    ["register"]=> "Value 3"
    ["link"]=> "link 3"
    ["approval"]=> "pending"
    ["image"]=> "image3.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
}

Ive tried flattening the array but this causes new issues since i will need to loop through each array and more values could be added later which will make it quite large, so i would like to keep each section in their own array so i can split it as needed later on.

Upvotes: 0

Views: 197

Answers (1)

Rohit Gaikwad
Rohit Gaikwad

Reputation: 815

try this

$arr = array(0=>array(1=>"dsfdsf",2=>"udyauyd"),1=>array(1=>"dsfdsf",2=>"udyauyd"),2=>array(1=>"dsfdsf",2=>"udyauyd"));
$arr1 = array(3=>"asdasd",4=>"fdsjldksfj",5=>"yerteruywet");
foreach($arr as $value)
{
  $new_array[] = $value + $arr1;
}

print_r($new_array);

I have use some sample array to demonstrate the logic.

Upvotes: 1

Related Questions