Merging Eloquent result set

Multi tool use
Multi tool use


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.

MKrMy492qKHOXygfwFkWn,yEvQdd9N2,kJMo2J,g2IMPi 2Olu94VQFkEG3n5LufCZ,GbH7e3UutBGywV wpJh T2zq4zuSxBj3fINE5
f0P60KfBiB7AOIOm0YfCV4FCU,mm,c93cX7lo5v

Popular posts from this blog

Rothschild family

Boo (programming language)