Azrael
Azrael

Reputation: 701

How to append MySQL array data to premade JSON?

I'm having trouble appending data returned from a MySQL table into a PHP JSON object. This is the premade object, and it works fine on its own. What I'd like to do is append extra data to this object.

$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.'"
}';

This is the data I'd like to append to the above object. How can I do this?

$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);

Query JSON Output example:

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

Upvotes: 0

Views: 154

Answers (1)

meda
meda

Reputation: 45490

Do not create JSON manually , it is very poor approach and your code will break one day

$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
);

Then it is very easy to append data:

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

Upvotes: 2

Related Questions