Reputation: 663
I have 2 different arrays
First is
(int) 0 => [
'id' => (int) 1,
'file_name' => 'test',
'imported_by' => 'John',
'valid_to' => (float) 1767225600000
],
(int) 1 => [
'id' => (int) 2,
'file_name' => null,
'imported_by' => 'John',
'valid_to' => (float) 1767225600000
],
Second one is
(int) 0 => object(App\Model\Entity\Product) {
'id' => (int) 1,
'product_cat' => (int) 10,
'product_type' => (int) 1,
'average....
I have to push first one into second one based on same key
it shoud look like this one
(int) 0 => object(App\Model\Entity\Product) {
'id' => (int) 1,
'product_category_id' => (int) 10,
'product_vessel_id' => (int) 1,
'average' => test;
//content from first array
'file_name' => 'test',
'imported_by' => 'John',
'valid_to' => (float) 1767225600000
I have tryied with array_merge_recursive($firstArray,$secondArray); but that mean adding elements on the end of firstArray
Upvotes: 0
Views: 493
Reputation: 25
You can use this function:
function merge_two_arrays($array1,$array2) {
$data = array();
$arrayAB = array_merge($array1,$array2);
foreach ($arrayAB as $value) {
$id = $value['id'];
if (!isset($data[$id])) {
$data[$id] = array();
}
$data[$id] = array_merge($data[$id],$value);
}
return $data;
}
$master_array = merge_two_arrays($array1,$array2);
Upvotes: 0
Reputation: 26
<?php
$result = array();
$array_one=array(0 => array('id' => 1,
'file_name' => 'test',
'imported_by' => 'John',
'valid_to' => 1767225600000),
1 => array(
'id' => 2,
'file_name' => "",
'imported_by' => 'John',
'valid_to' => 1767225600000)
);
$array_seond= array(
0 => array(
'id' => 1,
'product_cat' => 10,
'product_type' => 1,
'average' => 'test'
)
);
echo "<pre>";
//print_r($result);
foreach($array_seond as $key => $value){
foreach($array_one as $value_second ){
if($value['id']==$value_second['id']){
$result[$key] =array_merge($array_seond[$key],$value_second);
}
}
}
print_r($result);
?>
Upvotes: 0
Reputation: 3925
$array1 = array(...);
$array2 = array(...);
foreach ( $array1 as $element ) {
foreach ( $array2 as $object ) {
if ( $object->id == $element['id'] ) {
$object->filename = $element['filename'];
$object->imported_by = $element['imported_by'];
$object->valid_to = $element['valid_to'];
break;
}
}
}
Upvotes: 1