要将数据合并到单个响应并返回预期输出,请使用以下方法:
<code class="sql">SELECT subjects.userid, users.name AS username, ( SELECT id FROM tbsubjects WHERE userid = subjects.userid ORDER BY id ASC LIMIT 1 ) AS subjectsid, ( SELECT name FROM tbsubjects WHERE userid = subjects.userid ORDER BY time DESC LIMIT 1 ) AS subjectname, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND month = DATE_FORMAT(NOW(), "%c") ) AS activepts, IFNULL(SUM(subjects.points), 0) AS totalpts, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 1 ) AS sem1, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 2 ) AS sem2, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 3 ) AS sem3 FROM tbsubjects AS subjects LEFT JOIN tbusers AS users ON users.id = subjects.userid WHERE subjects.userid = :userid1 GROUP BY subjects.userid ORDER BY subjects.time DESC;</code>
如果用户列表为空,则返回 JSON 格式的错误消息:
<code class="php">$response->getBody()->write( '{ "error": { "message":"Invalid" } }' );</code>
否则,返回 JSON 编码的用户列表。
假设您的主题表与初始描述中的结构相同,您可以使用以下脚本获取并格式化所需的数据:
<code class="php"><?php $userid1 = 1; // Replace this with the actual user ID // SQL statement $sql = 'SELECT ... FROM ... WHERE subjects.userid = :userid1 GROUP BY ... ORDER BY ...'; // Bindings $bindings = array( ':userid1' => $userid1 ); // Fetch users $users = $dbAdapter->fetchAll($sql, $bindings); // Handle results if (empty($users)) { // Handle empty users list } else { // Handle users list }</code>
该脚本假设您有一个提供数据库交互方法的 DbAdapter 类。这个类应该处理连接建立、语句准备和数据检索。
以上是如何在 PHP 中的一个响应中返回多个响应数据?的详细内容。更多信息请关注PHP中文网其他相关文章!