gpt4 book ai didi

php - 如何将 MySQL 数组数据追加到预制 JSON 中?

转载 作者:行者123 更新时间:2023-11-29 07:58:28 25 4
gpt4 key购买 nike

我在将从 MySQL 表返回的数据追加到 PHP JSON 对象中时遇到问题。这是预制的对象,它本身工作得很好。我想做的是将额外的数据附加到该对象。

$profileData = '{
"uid": "'.$uid['id'].'",
"username": "'.$user.'",
"cover": "'.$userData['profile_cov'].'",
"propic": "'.$userData['profile_pic'].'",
"fullName": "'.$userData['full_name'].'",
"about": "'.$userData['about'].'",
"relationship": "'.$userData['relationship'].'",
"location": "'.$userData['location'].'",
"work": "'.$userData['work'].'",
"sexPref": "'.$userData['sex_pref'].'",
"edu": "'.$userData['education'].'",
"hometown": "'.$userData['hometown'].'",
"isFollowing": "'.$isFollowingResult.'",
"areFriends": "'.$areFriendsResult.'"
}';

这是我想要附加到上述对象的数据。我怎样才能做到这一点?

$getPosts = "SELECT `author`, `access`, `post`, `posted` FROM `posts` WHERE `author` =   '$userData[username]' AND `access` = 'Public' ORDER BY `posted` DESC";
$postResults = $cnct->query($getPosts);
$rows = array();
while($usrPosts = $postResults->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $usrPosts;
}
$data = array('Posts' => $rows);
echo json_encode($data);

查询 JSON 输出示例:

{"Posts":[{"author":"Elitis","access":"Public","post":"Test 4","posted":"2014-06-20 14:02:09"}]}

最佳答案

不要手动创建 JSON,这是一种非常糟糕的方法,您的代码有一天会损坏

$profileData = array(
'uid'=> $uid['id'],
'username'=>$user,
'cover'=>$userData['profile_cov'],
'propic'=>$userData['profile_pic'],
'fullName'=> $userData['full_name'],
'about'=> $userData['about'],
'relationship'=> $userData['relationship'],
'location'=> $userData['location'],
'work'=> $userData['work'],
'sexPref'=> $userData['sex_pref'],
'edu'=> $userData['education'],
'hometown'=> $userData['hometown'],
'isFollowing'=> $isFollowingResult,
'areFriends'=> $areFriendsResult
);

然后就很容易追加数据了:

profileData['Posts'] = $rows;
echo json_encode($profileData);

关于php - 如何将 MySQL 数组数据追加到预制 JSON 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24481694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com