laravel 5.3 中的对象访问问题?
Object access issue in laravel 5.3?
我在 json 中传递对象数组,并试图在 foreach 循环中访问它,但出现错误 "Trying to get property of non-object"
JSON
{"i":[{"name":"Siddhesh
mishra","mobile":"7798645895","gender":"M"},{"name":"Pratik
pande","mobile":"7798645891","gender":"M"}]
foreach 循环
foreach ($request->i as $key => $insrtobj) {
if($insrtobj->name && $insrtobj->mobile && $insrtobj->gender){
}
else
$response = response()->json(['data'=>[], 'error'=>1, 'success'=>0, 'error_msg'=>'request with mandatory param','message'=>'check the input data']);
}
将您的 JSON 数据转换成数组形式并使用它...:[=12=]
$arrData = json_decode(YOURJSONDATA, true);
foreach ($arrData as $key => $insrtData) {
//your rest of code...
}
注意:当为 TRUE 时,返回的对象将被转换为关联数组。 Docs
Laravel 请求对象使用 json_decode
自动解码 json 输入,但它传递 true
作为第二个参数以将对象转换为数组。因此,当从请求中访问 json 数据时,您需要将其视为关联数组,而不是对象。
if ($insrtobj['name'] && $insrtobj['mobile'] && $insrtobj['gender']) {
我在 json 中传递对象数组,并试图在 foreach 循环中访问它,但出现错误 "Trying to get property of non-object"
JSON
{"i":[{"name":"Siddhesh mishra","mobile":"7798645895","gender":"M"},{"name":"Pratik pande","mobile":"7798645891","gender":"M"}]
foreach 循环
foreach ($request->i as $key => $insrtobj) {
if($insrtobj->name && $insrtobj->mobile && $insrtobj->gender){
}
else
$response = response()->json(['data'=>[], 'error'=>1, 'success'=>0, 'error_msg'=>'request with mandatory param','message'=>'check the input data']);
}
将您的 JSON 数据转换成数组形式并使用它...:[=12=]
$arrData = json_decode(YOURJSONDATA, true);
foreach ($arrData as $key => $insrtData) {
//your rest of code...
}
注意:当为 TRUE 时,返回的对象将被转换为关联数组。 Docs
Laravel 请求对象使用 json_decode
自动解码 json 输入,但它传递 true
作为第二个参数以将对象转换为数组。因此,当从请求中访问 json 数据时,您需要将其视为关联数组,而不是对象。
if ($insrtobj['name'] && $insrtobj['mobile'] && $insrtobj['gender']) {