json - “消息”:“非法字符串偏移 'product_id'”,在 Laravel RESTfull API 中
问题描述
我正在开发 Laravel RESTful API,用于使用 php 关联数组将 Json 对象数组保存到 DB 中,这是我遇到的错误。
"message": "Illegal string offset 'product_id'",
"exception": "ErrorException",
...
这是我试图保存在 Mysql DB 中的 JSON 对象数组
"userId": "1",
"userName": "Dan",
"userEmail": "dan@gmail.com"
"product": [
{
"product_id": "31",
"product_name": "Orange",
"product_price": "USD 0.5"
}
]
}
这是将 Json 对象保存到 DB 中的 php 函数。
$userId = $request -> input('userId');
$userName = $request ->input('userName');
$userEmail = $request ->input('userEmail');
$data = array(
"userId"=>$userId,
"userName"=>$userName,
"userEmail"=>$userEmail
);
$user = User::create($data);
if($order){
//Storing the received JSON in $json.
$json = file_get_contents('php://input');
// Decode the received JSON and store into $obj
$obj = json_decode($json,true);
foreach($obj as $product){
$product_id = $product['product_id'];
$product_name = $product['product_name'];
$product_price = $product['product_price'];
$product = array(
"product_id" => $product_id,
"product_name" => $product_name,
"product_price" => $product_price
);
DB::table('products')->insert($product);
}
if($product){
// On query success it will print below message.
$MSG = 'Data Successfully Submitted.' ;
// Converting the message into JSON format.
$json = json_encode($MSG);
// Echo the message.
echo $json ;
}
else{
echo 'Try Again';
}
伙计们,我在哪里犯错。先感谢您!
解决方案
推荐阅读
- excel - 如何让 VBA 取消脚本?
- python - 基于使用的产品进行客户细分的 ML 模型
- python - Django 数据库关系 - TypeError: 'ManyToOneRel' 对象不可迭代
- vba - 删除按钮上方的单行但不允许删除,如果
- python - 403 gmail api与python的权限不足
- c# - WPF 和棱镜:单选按钮选择在多个用户控件上消失
- selenium - 硒表计数
- java - 如何处理浏览器弹出窗口(使用 Selenium WebDriver)?
- python - 如何使用 Paramiko getfo 将文件从 SFTP 服务器下载到内存进行处理
- python - uwsgi+flask 启动|停止 python 守护进程