【问题标题】:Really simple PHP array key-value issue非常简单的 PHP 数组键值问题
【发布时间】: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 抱歉 - 我确实看过但没有找到那个帖子

标签: php arrays json


【解决方案1】:

试试这个:

while ($row = mysql_fetch_array($res)) {
    $name     = $row['name'];
    $descript = $row['description'];
    $img      = $row['image'];

    $temp[$name] = array('name'=>$name,'description'=>$descript,'img'=>$img);
}

【讨论】:

  • 非常感谢 - 我不敢相信我没有想到这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2011-04-13
  • 1970-01-01
相关资源
最近更新 更多