query($sql); $posts = $stmt->fetchAll(); // 为每个post添加评论 foreach ($posts as &$post) { $commentSql = "SELECT c.id, u.username AS author, c.content FROM comments c JOIN users u ON c.user_id = u.id WHERE c.love_wall_id = :love_wall_id"; $commentStmt = $pdo->prepare($commentSql); $commentStmt->execute([':love_wall_id' => $post['id']]); $post['comments'] = $commentStmt->fetchAll(PDO::FETCH_ASSOC); // 确保是关联数组 // TODO: 头像 $post['avatar'] = '/placeholder.svg?height=40&width=40'; // 清理不需要的索引 $post = [ 'id' => $post['id'], 'author' => $post['author'], 'avatar' => $post['avatar'], 'content' => $post['content'], 'likes' => (int)$post['likes'], // 转换为整数 'comments' => $post['comments'] ]; } echo json_encode($posts, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); ?>