2
PHP - JSON编码的问题PHP - JSON编码的问题
我目前正在开发一个Android应用程序作为我学校项目的一部分。我需要设置一个API,它将从数据库中检索 所有讲座,并将它们输出为JSON。这里有一个例子,我多么希望他们输出:
{
"count: 4,
"msg": "",
"user_id": 1,
"name": "John Doe"
"lectures": [{
"id": 1,
"starting_at": "2015-11-30 13:00",
"ending_at": "2015-11-30 15:00",
"course_name": "Name of Course #1",
}, {
"id": 2,
"starting_at": "2015-11-30 13:00",
"ending_at": "2015-11-30 15:00",
"course_name": "Name of Course #2",
}, {
"id": 3,
"starting_at": "2015-11-30 13:00",
"ending_at": "2015-11-30 15:00",
"course_name": "Name of Course #3",
}]
}
但是,相反,它重复检索到的所有对象和我的输出是这样的:
{
"count":4,
"msg":"",
"lectures":[{
"id":"1",
"0":"1", // Duplicated object
"starting_at": "2015-11-30 13:00:00",
"1":"2015-11-30 13:00:00", // Duplicated object
"ending_at":"2015-11-30 15:00:00",
"2":"2015-11-30 15:00:00", // Duplicated object
"user_id":"1",
"3":"1", // Duplicate object
"course":"Course Name #1",
"4":"Course Name #1", // Duplicated object
"user_name":"John Doe",
"5":"John Doe"
}, {
"id":"2",
"0":"2", // Duplicated object
"starting_at": "2015-11-30 13:00:00",
"1":"2015-11-30 13:00:00", // Duplicated object
"ending_at":"2015-11-30 15:00:00",
"2":"2015-11-30 15:00:00", // Duplicated object
"user_id":"1",
"3":"1", // Duplicated object
"course": "Course Name #2",
"4":"Course Name #2", // Duplicated object
"user_name":"John Doe",
"5":"John Doe" // Duplicated object
]}
}
我不得不承认,我对于JSON来说相对来说比较新,而且肯定需要一些帮助。这里是我的API调用PHP:
<?php
require_once("dbconnect.php");
$user_id = 1;
// Prepare the statement
$stmt = $pdo->prepare("
SELECT
lectures.id,
lectures.starting_at,
lectures.ending_at,
users_lectures.user_id,
courses.name AS course,
users.name AS user_name
FROM lectures
LEFT JOIN courses ON courses.id = lectures.course_id
LEFT JOIN users_lectures ON users_lectures.lecture_id = lectures.id
LEFT JOIN users ON users.id = users_lectures.user_id
WHERE users_lectures.user_id = :user_id
AND lectures.starting_at >= CURRENT_DATE()
ORDER BY lectures.starting_at DESC");
$stmt->execute(array(':user_id' => $user_id));
if($stmt->rowCount() > 0) {
$lectures = array();
while ($row = $stmt->fetch()) {
$lectures[] = $row;
}
echo json_encode(["count" => count($lectures), "msg" => "", "user_id" => $row['user_id'], "name" => $row['user_name'], "lectures" => [$lectures]]);
} else {
echo json_encode(["count" => 0, "msg" => "No lectures today"]);
}