gpt4 book ai didi

php - 解析多个json对象并将其存储在数据库中

转载 作者:行者123 更新时间:2023-11-29 21:42:42 27 4
gpt4 key购买 nike

我需要从 JSON 文件中解析这多个 JSON 对象。 JSON 文件包含数千个 JSON 对象,现在我需要解析所有这些 JSON 对象,所以请任何人尝试解决这个问题,然后我再次需要将所有 JSON 数据存储到 MySQL。

{
{
"name": "Michael Bruce",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Jennifer Winters",
"gender": "Female",
"designation": "Senior Programmer"
},
{
"name": "Donna Fox",
"gender": "Female",
"designation": "Office Manager"
},
{
"name": "Howard Hatfield",
"gender": "Male",
"designation": "Customer Support"
}
}

{
{
"name": "aMichael Bruce",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Jennifer Winters",
"gender": "Female",
"designation": "Senior Programmer"
},
{
"name": "Donna Fox",
"gender": "Female",
"designation": "Office Manager"
},
{
"name": "Howard Hatfield",
"gender": "Male",
"designation": "Customer Support"
}
}

{
{
"name": "Michael Bruce",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Jennifer Winters",
"gender": "Female",
"designation": "Senior Programmer"
},
{
"name": "Donna Fox",
"gender": "Female",
"designation": "Office Manager"
},
{
"name": "Howard Hatfield",
"gender": "Male",
"designation": "Customer Support"
}
}

以及我的代码。

<?php

$host = "localhost";
$username = "root";
$password = "";
$dbname = "employee";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));

$st = mysqli_prepare($con, 'INSERT INTO emp(name, gender, designation) VALUES (?, ?, ?)');

mysqli_stmt_bind_param($st, 'sss', $name, $gender, $designation);

$filename = 'file3.json';
$json = file_get_contents($filename);
$data = json_decode($json, true);

foreach ($data as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {

$name = $key['name'];
$gender = $key['gender'];
$designation = $key['designation'];
echo $name;
mysqli_stmt_execute($st);
}
}
}

mysqli_close($con);
?>

上面的代码仅适用于一个 JSON 对象,假设我的文件中有多个 JSON 对象,然后它会抛出类似的错误。

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\jumadi\b\c\index2.php on line 25

最佳答案

首先json是错误的。外括号必须是方形的,因为这应该是数组。

其次,检索代码从 key 读取而不是从 val 读取。应该是:

 $name = $val['name'];
... etc

关于php - 解析多个json对象并将其存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34367769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com