Php 如何将MySQL数组数据附加到预制JSON中?

Php 如何将MySQL数组数据附加到预制JSON中?,php,mysql,json,Php,Mysql,Json,我在将MySQL表返回的数据添加到PHP JSON对象时遇到问题。 这是预先制作的对象,它自己可以正常工作。我想做的是向这个对象附加额外的数据 $profileData = '{ "uid": "'.$uid['id'].'", "username": "'.$user.'", "cover": "'.$userData['profile_cov'].'", "propic": "'.$userData['profile_pic'].'", "fullNa

我在将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);

您能否提供一个从数据库查询/JSON输出中获得的输出示例?如果数据结构相同,您应该能够将两个数组一起
array\u merge()
,然后对其进行编码。如果它们不是相同的数据结构,您需要使它们相同,然后按照上面的第一步进行操作。更新的操作。这就是您想要的吗@具体来说,是什么让手动创建JSON成为一种糟糕的做法?另外,使用这种方法,我将如何访问客户端的帖子?x、 Posts.post?@Azrael这是一个糟糕的做法,因为PHP有一个内置函数来为您处理它,虽然该函数将始终保持最新的当前标准、错误修复、问题等,但您的自定义函数将不会(因为您不想!)。这里最好使用
json\u encode()