我試圖解碼與一個循環,插入的所有對象,以我的DB一個JSON,下面是我的PHP代碼,但我有錯誤:致命錯誤:無法使用類型stdClass的對象爲陣列中phptest.php第21行解碼JSON數組錯誤
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
foreach($request as $key => $value) {
$equip = $value['equipment'];
$sql = "INSERT INTO contratos (equipo) VALUES ('$equip')";
}
}
我發佈具有角的JSON,下面的代碼是我controller.js
$scope.continue = function(choices)
{
var data = $scope.choices;
$http.post('php/phptest.php', data)
.then(function(response) {
console.log(response);
});
};
而JSON
[
{
"id":"choice1",
"quantity":1,
"equipment":"BLONG - F25",
"teamvox":true,
"plandatos":"D50"
},
{
"id":"choice2",
"quantity":1,
"equipment":"OUTERFONE - S17",
"evidence":true,
"mobictrl":true,
"plandatos":"D100"
}
]
你應該只運行你的foreach一次。 – Daerik
'$ postdata'的var_dump是什麼樣的?因爲我想知道它是否將js中的對象轉換爲後值,並且發佈的數據不是json。 [因爲這裏發佈的json似乎沒有什麼問題](https://3v4l.org/T1Nme) –
試試'json_decode($ postdata,true)'強制結果成爲關聯數組 – Phil