【发布时间】:2011-09-30 22:36:31
【问题描述】:
假设我的数据库中有下表:
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() 函数 - 我希望它以名称作为键来推送,但我无法得到它。
【问题讨论】:
-
array_push()将创建一个堆栈,而不是关联数组,这意味着它不是您想要的。只需使用键控值并将其设置为键控/关联数组。 -
@Mark 抱歉 - 我确实看过但没有找到那个帖子