从PHP Query获取特定格式的JSON

时间:2014-04-24 03:49:45

标签: php mysql json

我想得到一个这样的数组:

{
    "version": "1397992135_1932",
    "list": {
        "20514072":["John Carter","FiExJGIpsek.jpg",1],
        "7247045":["Joe Satriani","KzvE54Z4rlA.jpg",0],
        "91120813":["Mikel Arteta","JnPwkLKGeCA.jpg",1]
    }
}

在数据库中我有简单的行:

id | name | photo | vip

如何将查询结果格式化为我想要的内容?

更新

如果我有100条记录,我真的不明白如何对此进行编码以从数据库中获取数据。

2 个答案:

答案 0 :(得分:1)

这将是实现您正在寻找的JSON字符串所需的数组设置:

$data = array(
        "version" => "1397992135_1932",
        "list" =>
    array(
        "20514072" => array(
        "John Carter",
        "iExJGIpsek.jpg",
         "1"
         ),
        "7247045" => array(
        "Joe Satriani",
        "KzvE54Z4rlA.jpg",
        "0"
        ),
        "91120813" => array(
        "Mikel Arteta",
        "JnPwkLKGeCA.jpg",
        "1"
    ))
);

echo "<pre>";   
echo json_encode($data);
echo "</pre>";
?>

输出:

{
    "version":"1397992135_1932",
    "list":{
        "20514072":["John Carter","iExJGIpsek.jpg","1"],
        "7247045":["Joe Satriani","KzvE54Z4rlA.jpg","0"],
        "91120813":["Mikel Arteta","JnPwkLKGeCA.jpg","1"]
    }
}

答案 1 :(得分:1)

好的,我找到了动态数组的解决方案=)

$list = array();
while ($row = $result->fetch_array()) {
    $list[$row['id']] = array($name,$photo,$vip);
}