Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hecate0211's avatar

join 2 array

i have 2 array and i want to combine the array like this

array 1 like this (btw this array i got from query and make it to array
array:868 [▼
  0 => {#229 ▼
    +"id": 1
    +"name": "name"
    +"price": "98,302,820.00"
  }
  1 => {#229 ▼
    +"id": 2
    +"name": "name2"
    +"price": "98,302,820.00"
  }
array 2 like this(btw this array i got from query, and in my php i using array_push from array 1 to select where id array 1 = array 2 id)
array:434 [▼
  0 => array:2 [▼
    "created_at" =>  "2017-01-12 21:00:01"
    "updated_at" =>  "2017-01-13 13:00:02"
  ]
  1 => array:2 [▼
    "created_at" =>  "2017-01-12 21:00:01"
    "updated_at" =>  "2017-01-13 13:00:02"
  ]

and i want to join this 2 array like this

array:868 [▼
  0 => {#229 ▼
    +"id": 1
    +"name": "name"
    +"price": "98,302,820.00"
+"created_at": "2017-01-12 21:00:01"
      +"updated_at": "2017-01-13 13:00:02"
  }
  1 => {#229 ▼
    +"id": 2
    +"name": "name2"
    +"price": "98,302,820.00"
    +"created_at": "2017-01-12 21:00:01"
    +"updated_at": "2017-01-13 13:00:02"
  }
0 likes
6 replies
matt_panton's avatar

Assuming you have the two arrays in variables $arr1 and $arr2 you could combine them using

$arr3 = array_map('array_merge', $arr1, $arr2);
hecate0211's avatar

@tisuchi i tried using array_merge() but the resulut will like this

array:868 [▼
  0 => {#229 ▼
    +"id": 1
    +"name": "name"
    +"price": "98,302,820.00"
  }
  1 => {#229 ▼
    +"id": 2
    +"name": "name2"
    +"price": "98,302,820.00"
  }
 3 => array:1 [▼
    0 => {#672 ▼
      +"created_at": "2017-01-12 21:00:01"
      +"updated_at": "2017-01-13 13:00:02"
    }
  ]
 4 => array:1 [▼
    0 => {#672 ▼
      +"created_at": "2017-01-12 21:00:01"
      +"updated_at": "2017-01-13 13:00:02"
    }
  ]
tisuchi's avatar
tisuchi
Best Answer
Level 70

@hecate0211

I gave you wrongly. I make a sample example for you. Don't forget to adjust based on your data-


//array one
$myarray = array(
        ['name', 'work', 'time'],
        ['name', 'work', 'time'],
);


//array 2 that you want to merge with array 1
$myarray2 = array(
        ['created_at', 'updated_at'],
        ['created_at', 'updated_at'],
);



$finalArray = [];


foreach ($myarray as $key => $value) {

    array_push($finalArray, array_merge($value, $myarray2[$key]));
}



//it will print after combining two array
foreach ($finalArray as $value) {
    foreach ($value as $v) {
        echo $v . '<br/>';
    }
}

6 likes
matt_panton's avatar

@hecate0211 You don't actually call the array_merge function, you pass it as the first parameter to the array_map function.

Please or to participate in this conversation.