如何用分形在Json中显示数组



我想将带有数组的REST API数据保存到数据库中,它的工作,所有值都保存到表中,但当我想在json中查看结果时仍然会出错。

这是我的错误

"message": "Argument 1 passed to App\Transformers\NewLoanOfferTransformer::transform() must be an instance of App\Model\AntiAttrition, array given, called in /home/insko23/testing.insko.my/vendor/league/fractal/src/Scope.php on line 338",

我的控制器

public function new_loan_offer(Request $request, AntiAttrition $antiattrition)
{
$new = array_map(null, $request->mo_id, $request->id_clrt,$request->TaskID,$request->ACID,$request->CustIDNo);
foreach($new as $new) {
$request                  = new AntiAttrition;
$request->mo_id           = $new[0]; 
$request->id_clrt         = $new[1];  
$request->TaskID          = $new[2]; 
$request->ACID            = $new[3]; 
$request->CustIDNo        = $new[4]; 
$request->save();
}
$response = fractal()
->item($new)
->transformWith(new NewLoanOfferTransformer)
->toArray();
return response()->json($response,201);
}

我的应用程序\转换器

<?php
namespace AppTransformers;
use AppModelAntiAttrition;
use AppModelSettlementInfo;
use LeagueFractalTransformerAbstract;
class NewLoanOfferTransformer extends TransformerAbstract
{
	public function transform (AntiAttrition $antiattrition)
	{
		return[
			'id' => $antiattrition->id,
			'mo_id'=> $antiattrition->mo_id,
			'assign_by'=> $antiattrition->assigned_by,
			'id_clrt' => $antiattrition->id_clrt,
			'TaskID'=> $antiattrition->TaskID,
			'ACID'=> $antiattrition->ACID,
			'CustIDNo'=> $antiattrition->CustIDNo
		];
	}
}

我想在json中显示结果,就像下面的一样

{
"data": [
{
"mo_id": "123",
"id_clrt": "10000000049",
"ACID": "123",
.....
},
{
"mo_id": "1234",
"id_clrt": "10000000045",
"ACID": "1235",
.....
},
{
"mo_id": "124",
"id_clrt": "10000000044",
"ACID": "1245",
.....
},
],
}

请帮我解决这个问题

在foreach循环中,避免对数组和要迭代的数组的元素使用相同的名称,可以将foreach($new as $new)重命名为foreach($newArray as $new),或者对代码逻辑进行有意义的重命名。此外,不使用$new[0],而是使用$new['mo_id']来引用阵列的密钥

最新更新