我得到以下JSON格式的数据。
{"Students":
[{"ID":"600","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"601","datetime":"26-11-2019 04-32-31","age":"13"},
{"ID":"602","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"603","datetime":"26-11-2019 04-32-31","age":"14"}
]}我想编写一个PHP脚本来在MYSQL中插入这些数据。
我不知道如何编写循环来遍历这些数据。
我尝试了下面的代码,但它不起作用。
//encode the Json request.
$obj = json_decode($content);
foreach($obj as $key){
// $email = $decode['RouteID'];
}发布于 2019-11-28 13:21:34
// creating connection to mysql
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=DatbaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$content = '{"Students":
[{"ID":"600","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"601","datetime":"26-11-2019 04-32-31","age":"13"},
{"ID":"602","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"603","datetime":"26-11-2019 04-32-31","age":"14"}
]}';
$data= json_decode($content);
foreach($data->Students as $student){
$sql = "INSERT INTO users (ID, datetime, age) VALUES (?,?,?)";
$conn->prepare($sql)->execute([$student->ID, $student->datetime, $student->age]);
}发布于 2019-11-28 13:19:02
$json = '{"Students":
[{"ID":"600","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"601","datetime":"26-11-2019 04-32-31","age":"13"},
{"ID":"602","datetime":"26-11-2019 04-32-31","age":"12"},
{"ID":"603","datetime":"26-11-2019 04-32-31","age":"14"}
]}';
//convert json to array
$array = json_decode($json, true);
//loop
foreach($array['Students'] as $key => $val){
echo "$key = $val \n";
}
//or print whole array
print_r($array);print_r的结果如下:
(
[Students] => Array
(
[0] => Array
(
[ID] => 600
[datetime] => 26-11-2019 04-32-31
[age] => 12
)
[1] => Array
(
[ID] => 601
[datetime] => 26-11-2019 04-32-31
[age] => 13
)
[2] => Array
(
[ID] => 602
[datetime] => 26-11-2019 04-32-31
[age] => 12
)
[3] => Array
(
[ID] => 603
[datetime] => 26-11-2019 04-32-31
[age] => 14
)
)
)发布于 2019-11-28 13:17:14
要循环遍历对象并获取其成员,可以尝试以下操作:
foreach($json as $obj){
echo $obj->name;
.....
}使用$key是行不通的!
https://stackoverflow.com/questions/59089726
复制相似问题