在 Laravel 中返回 Response()->Json 和数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47862149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return Response()->Json and Arrays in Laravel
提问by Matthew
I have a controller that I would like to return a JSON response that has multiple arrays. First, I'll present my controller:
我有一个控制器,我想返回一个包含多个数组的 JSON 响应。首先,我将展示我的控制器:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}
This is an example, but at this time if I just dd($billToEmail), I will get multiple rows returned of all of the data that I requested (all of which are emails), but when I return the JSON specific return "billersEmails", I only get one of those emails returned.
这是一个例子,但此时如果我只是 dd($billToEmail),我将得到我请求的所有数据(所有这些都是电子邮件)的多行返回,但是当我返回 JSON 特定返回“bilersEmails ",我只收到其中一封电子邮件的回复。
I know there must be a possibility of the multiple emails being returned, but I haven't found an appropriate response anywhere as of yet.
我知道肯定有可能返回多封电子邮件,但到目前为止我还没有在任何地方找到合适的回复。
回答by B. Desai
You have to use array as you have multiple records otherwise it will over-write existing values. change your code as below:
您必须使用数组,因为您有多个记录,否则它会覆盖现有值。更改您的代码如下:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
$billToEmail = array();
$shipToEmail = array();
$shipFromEmail = array();
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail[] = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail[] = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail[] = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}