我正在尝试通过PHP将来自Mysql数据库的数据编码为JSON格式。这是代码段:
try
{
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
$rows = $statement->fetchAll();
echo print_r($rows)."<br/>";
foreach($rows as $row)
{
foreach($row as $a)
{
$studentInfo = array();
$studentInfo["course"] = $a["coursename"];
$studentInfo["grade"] = $a["grade"];
array_push($response['info'], $studentInfo);
}
}
echo json_encode($response);
}
但我无法将此数组编码为JSON。
print_r($rows)
打印以下内容:
Array (
[0] => Array (
[id] => 22222
[coursename] => sp1
[grade] => B
)
[1] => Array (
[id] => 22222
[coursename] => sw1
[grade] => A-
)
[2] => Array (
[id] => 22222
[coursename] => sw2
[grade] => B+
)
)
1
echo json_encode($response)
打印以下内容:
{"info":null}
有人可以告诉我如何将这个数组解析成JSON吗? 我想以JSON格式学习每门课程及其成绩。
答案 0 :(得分:2)
try
{
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
$rows = $statement->fetchAll();
echo print_r($rows)."<br/>";
$response=array();
$info=array();
foreach($rows as $row)
{
$studentInfo = array();
$studentInfo["id"]=$row["id"];
$studentInfo["course"] = $row["coursename"];
$studentInfo["grade"] = $row["grade"];
array_push($info, $studentInfo);
}
$response['info']=$info;
echo json_encode($response); // or echo json_encode($info);// whatever you want
}
答案 1 :(得分:1)
我会做这样的事情:
try {
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
if($result) {
$arr = Array();
while ($row = $result->fetch_assoc()) {
$arr[] = $row;
}
echo json_encode($arr);
}
}
答案 2 :(得分:0)
json_encode()可以直接对数组进行编码。
在您的代码第8行,可以执行此操作
echo json_encode($rows);
请点击此处参考以获取更多信息 http://php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
输出:
{&#34;&#34;:1,&#34; B&#34;:2&#34; C&#34;:3,&#34; d&#34:4,&#34; E& #34;:5}