Reputation: 13371
Let's say I have the following table in my database:
Name | Description | Image
App | Some description | somefile.png
Another App | Another descript | anotherfile.png
What I want to do is create a JSON array like this:
{
"App": {
"name": "App",
"description": "Some description",
"Image": "somefile.png"
},
"Another App": {
"name": "Another App",
"description": "Another descript",
"Image": "anotherfile.png"
}
}
What I'm struggling with is pushing the key>value pair on. I can push just the value, with a non-keyed array, but I cannot push the key>value pair onto my array.
What I've tried:
$res = mysql_query('SELECT * FROM `apps`;');
if ($res) {
$temp = array();
while ($row = mysql_fetch_array($res)) {
$name = $row['name'];
$descript = $row['description'];
$img = $row['image'];
$new = array('name'=>$name,'description'=>$descript,'img'=>$img);
array_push($temp,$new); // how do I make this push with a key?
}
}
echo json_encode($temp);
My problem is with the array_push() function - I want it to push with the name as the key but I can't get it to.
Upvotes: 0
Views: 211
Reputation: 69967
Try this:
while ($row = mysql_fetch_array($res)) {
$name = $row['name'];
$descript = $row['description'];
$img = $row['image'];
$temp[$name] = array('name'=>$name,'description'=>$descript,'img'=>$img);
}
Upvotes: 2