Laravel 4.2 Merging Two Eloquent Object By Index

118 views Asked by At

Hello guys I need your help as I am working on very old version of laravel i.e 4.1 What I want is I have two eloquent object they don't have any relation between them. Now I have below example which combine two array by their index I mean if I want to merge one array data to another one then this is my way to merge both array data. 1, 'product_name' => 'product1', 'price' => 200 ], // First element ['product_id' => 2, 'product_name' => 'product2', 'price' => 400 ] // Second Element ]; $array2 = [ ['color' => 'red', 'size' => 'M'], // First Element ['color' => 'blue', 'size' => 'L'] // Second Element ];

$singleArray = []; // Third blank array.
foreach ($array1 as $key1 => $value1) {
$value2 = $array2[$key1]; // Get each element of second array by first array key
$singleArray[$key1] = $value1 + $value2;// Combine both array in third array 
}
Output of the two array merging,
array
(
[0] => array
(
[product_id] => 1 // First Array Element
[product_name] => product1 // First Array Element
[price] => 200 // First Array Element
[color] => red // Second Array Element
[size] => M // Second Array Element
)

[1] => array
(
[product_id] => 2 // First Array Element
[product_name] => product2 // First Array Element
[price] => 400 // First Array Element
[color] => blue // Second Array Element
[size] => L // Second Array Element
)
)

Now my requirement is I need third eloquent object which has a records from both the object (In case of laravel 4.1) I tried it with merge but merge append the object2 records to the object1 records
But What happens is , It created new index for records in object2 F

or example,  I have object1 and object2 ,
     What I got is,
Object(
[0] => array // First element of first object
(
[product_id] => 1
[product_name] => product1
[price] => 200
)
[1] => array // Second element of first object
(
[product_id] => 2
[product_name] => product2
[price] => 400
)
[2] => array // First element of second object
(
[color] => red
[size] => M
)
[4] => array // Second element of second object
(
[color] => blue
[size] => L
)
)
Which I don't want, What I want is,

I need the same output as we got in merging of array but in terms of eloquent result.

1

There are 1 answers

0
AudioBubble On

You can loop through the first object and parse the second object and save it to your first object's element the same way you did with arrays. You can refer this to set a new attribute Manually add item to existing object [Laravel 5]