Merging Eloquent result set


Merging Eloquent result set



I have two eloquent outputs


allowance Amount
A 100
B 80
C 120
D 150



AND


Deductions Amount
X 50
Y 60
Z 70



and json appears as


$allowance = [{"allname":"A","allamount":"100"},{"allname":"B","allamount":"80"},{"allname":"C","allamount":"120"},{"allname":"D","allamount":"150"}]
$Deductions = [{"dedname":"X","dedamount":"50"},{"dedname":"Y","dedamount":"60"},{"dedname":"Z","dedamount":"70"}].



I want new json to be like


$new = [{"allname":"A","allamount":"100","dedname":"X","dedamount":"50"},{"allname":"B","allamount":"80","dedname":"Y","dedamount":"60"},{"allname":"C","allamount":"120","dedname":"Z","dedamount":"70"},{"allname":"D","allamount":"150"}]



Kindly guide me. Thanks in advance.





laravel.com/docs/5.6/collections#method-merge (and yes Eloquent returns collections when using get() (not first())
– Thomas Moors
Jul 2 at 10:11


get()


first()




2 Answers
2



Lets say you have two collections


$firstCollection = collect(['one','two']);

$collectionTwo = collect(['three','four']);

$firstCollection->merge($collectionTwo);



using merge() will merge the two collections.


merge()



Try this code you can get what do you want:


$a = array(array('allname' =>'A','allamount'=>'100'),
array('allname' =>'B','allamount'=>'200'),
array('allname' =>'C','allamount'=>'300'));

$b = array(array('dedname' =>'X','dedamount'=>'50'),
array('dedname' =>'c','dedamount'=>'150'));

$all=array();

for ($i=0; $i < count($a); $i++) {

$merged="";

if (isset($b[$i])) {

$merged=array_merge($a[$i],$b[$i]);

}else{

$merged=$a[$i];
}

$all=$merged;
}

echo "<pre>";print_r($all);echo "<br";

header('Content-Type: application/json');

echo json_encode($all);



output:



[{"allname":"A","allamount":"100","dedname":"X","dedamount":"50"},{"allname":"B","allamount":"200","dedname":"c","dedamount":"150"},{"allname":"C","allamount":"300"}]



I hope this could help you.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?