Am正在开发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对象保存到数据库中的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';
}
我在哪里弄错。预先谢谢你!