Reputation: 665
So I'm trying to build a JSON object with an array nested inside the main users array.
I'm having a bit of trouble building the data model in the PHP. Can anyone give any pointers?
Desired output:
[{
id: 2,
name: "John Wilson",
profilePic: "fighter-1.jpg",
activities: [{
id: 6431,
time: (57).minutes().ago(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}]
}, {
id: 3,
name: "Christoper Robin",
profilePic: "fighter-3.jpg",
activities: [{
id: 6431,
time: (1).days().ago,
points: 20
}, {
id: 6431,
time: (2).days().ago,
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}]
}, {
id: 1,
name: "Jerry Seinfeld",
profilePic: "placeholder.jpg",
activities: [{
id: 6431,
time: new Date(),
points: 20
}, {
id: 6431,
time: new Date(),
points: 20
}, {
id: 6432,
time: new Date(),
points: 100
}]
}]
The PHP and MySQL:
$getCompUsers = mysql_query("SELECT c.userid, u.name, u.profilePic, a.activity_typeid, a.userid, a.time, a.activity_weight, a.activityname
FROM competitionmembers c
INNER JOIN users1 u ON u.id = c.userid
INNER JOIN activity_entries a ON a.userid = u.id
WHERE c.competitionid = '$competitionId'") or die("Couldn't select competitions users");
$compUsersArr = array();
while ($row = mysql_fetch_array($getCompUsers,MYSQL_ASSOC)){
$compUsersArr = array(
'id' => $row["userid"],
'name'=> $row["name"],
'profilePic' => $row["profilePic"],
$activities = array( //THIS SEEMS TO BE THE PROBLEM
'id' => $row["activity_typeid"],
'name' => $row["activityname"],
'points' => $row["activity_weight"]
)
);
}
Upvotes: 1
Views: 90
Reputation: 23480
The way you are making your array is wrong, to nest arrays
you don't have to use variables in array as you did
$compUsersArr = array(
'id' => $row["userid"],
'name'=> $row["name"],
'profilePic' => $row["profilePic"],
'activities' => array(
'id' => $row["activity_typeid"],
'name' => $row["activityname"],
'points' => $row["activity_weight"]
)
);
Upvotes: 2
Reputation: 173532
Actually, your code was almost correct; splitting it up will make you see why it didn't:
$activities = array(
'id' => $row["activity_typeid"],
'name' => $row["activityname"],
'points' => $row["activity_weight"]
);
$compUsersArr = array(
'id' => $row["userid"],
'name'=> $row["name"],
'profilePic' => $row["profilePic"],
$activities,
);
This will create an array like:
[
'id' => 123,
'name' => 'foo',
'profilePic' => 'bar',
0 => ['id' => 456, 'name' => 'baz', 'points' => 'quz']
]
You would probably want this:
$compUsersArr = array(
'id' => $row["userid"],
'name'=> $row["name"],
'profilePic' => $row["profilePic"],
'activities' => $activities,
);
Upvotes: 1