我无法将从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"}]}
答案 0 :(得分:2)
不要手动创建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);