假设我的数据库中有以下表格:
Name | Description | Image
App | Some description | somefile.png
Another App | Another descript | anotherfile.png
我想要做的是创建一个像这样的JSON数组:
{
"App": {
"name": "App",
"description": "Some description",
"Image": "somefile.png"
},
"Another App": {
"name": "Another App",
"description": "Another descript",
"Image": "anotherfile.png"
}
}
我正在努力的是推动关键的>值对。我可以使用非键控数组来推送值,但是我无法将键>值对推到我的数组上。
我尝试了什么:
$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);
我的问题在于array_push()函数 - 我希望它以名称作为键推送,但我无法将其推送到。
答案 0 :(得分:2)
试试这个:
while ($row = mysql_fetch_array($res)) {
$name = $row['name'];
$descript = $row['description'];
$img = $row['image'];
$temp[$name] = array('name'=>$name,'description'=>$descript,'img'=>$img);
}