我正在尝试使用php将记录插入mysql,但我不知道如何在php中实现这一点: 基本上我有以下json数组:
[{StudentId:236,"Monday":null,"Tuesday":"2","Wednesday":"3","Thursday":"4","Friday":null},{StudentId:237,"Monday":null,"Tuesday":null,"Wednesday":"3","Thursday":"4","Friday":"5"}]
MySQL表架构如下:
Id |学生|天
1 | 236 | 2
2 | 236 | 3
3 | 236 | 4
4 | 237 | 3
5 | 237 | 4
我正在使用以下代码循环并获取值,但它没有显示每一天。我是否应该创建学生参加的所有日子的另一个数组然后循环?请和建议将不胜感激。谢谢。
$arr = json_decode($output,true);
foreach ($arr as $key => $jsons)
{
$day=null;
$student=null;
foreach($jsons as $key => $value)
{
if($key == 'StudentId')
{
$student = $value;
}
if($key == 'Monday')
{
if($value == '1')
{
$day = 1;
}
}
if($key == 'Tuesday')
{
if($value == '2')
{
$day = 2;
}
}
}
echo "INSERT INTO MyTable (Student,Day) VALUES($student,$day);";
echo '<br/>';
}
答案 0 :(得分:0)
您有一组键/值对数组,但根据您的代码,您有两个键/值对数组。请参阅以下内容如何影响您的代码,并使用print
语句来帮助调试。
更改:foreach ($arr as $key => $jsons)
至:foreach ($arr as $jsons)
答案 1 :(得分:0)
看起来你的JSON字符串格式不正确。此示例工作正常:
$json = <<<JSON
[
{
"StudentId": 236,
"Monday": null,
"Tuesday": "2",
"Wednesday": "3",
"Thursday": "4",
"Friday": null
},
{
"StudentId": 237,
"Monday": null,
"Tuesday": null,
"Wednesday": "3",
"Thursday": "4",
"Friday": "5"
}
]
JSON;
$arr = json_decode($json, true);
foreach ($arr as $student) {
foreach ($student as $key => $value) {
if ($key == 'StudentId') {
$student = $value;
}
if ($key == 'Monday') {
if ($value == '1') {
$day = 1;
}
}
if ($key == 'Tuesday') {
if ($value == '2') {
$day = 2;
}
}
}
echo "INSERT INTO MyTable (Student,Day) VALUES($student,$day);\n";
echo '<br/>';
}
结果是:
INSERT INTO MyTable (Student,Day) VALUES(236,2);
INSERT INTO MyTable (Student,Day) VALUES(237,2);