如何在PHP数组中存储MySQL表

时间:2013-12-15 22:41:51

标签: php json

我试图将所有值存储在MySQL数据库中名为locations的表中,该表看起来像

enter image description here

到名为$locations = array();的PHP数组中。我需要以格式(Associated array或Regular)存储数据,我可以使用php的json_encode()函数将它们转换为JSON文件。最终输出必须看起来像

{
    "markers": [{
        "id": 1,
        "type": "shelter",
        "lat": 55.6295639,
        "long": 12.6392556,
        "latlong": "55.6295639,12.6392556"
    }, {
        "id": 2,
        "type": "shelter",
        "lat": 49.6125639,
        "long": 12.6392556,
        "latlong": "55.6295639,12.6392556"
    }, {
        "id": 3,
        "type": "shelter",
        "lat": 56.6786339,
        "long": 11.6392556,
        "latlong": "55.6295639,12.6392556"
    }, {
        "id": 4,
        "type": "shelter",
        "lat": 51.6295639,
        "long": 13.6392556,
        "latlong": "55.6295639,12.6392556"
    }, ]
}

我已经尝试过此代码,但不确定我做得对吗?或者如何将它导出到json?

$result = mysql_query('select * from locations');

$locations = array();
while($r = mysql_fetch_array($result) {
    $row = array();
    foreach($r as $k=>$v) {
         $row[$k] = $v;
    }
    array_push($locations,$row);
    unset($row);
} 

3 个答案:

答案 0 :(得分:2)

我想你可以:

$result = mysql_query('select * from locations');
$locations = array();

while($row = mysql_fetch_array($result) {
    array_push($locations, $row);
} 

//echo json_encode($locations)

答案 1 :(得分:2)

当你调用mysql_fetch_array()时,返回的行已经是一个关联的数组。然后你可以做的是将该行存储在另一个数组中(实际上现在是一个二维数组),但是你也希望该数组是关联的。如果你遵循Floris的方法,你就可以很好地达到你想要的结果,所以我只是提供一个替代方案,每一行都为你的JSON导出获得某种有意义的标签

注意:不推荐使用mysql_ *函数。我只是出于举例的目的而使用它们。请发表评论或发送消息,我将发布mysqli版本。

$result = mysql_query('select * from locations');
$locations = array();
$i=0;
while($row = mysql_fetch_array($result)){
    $locations['location_'.$i] = $row;
    $i++;
}

echo json_encode($locations);

编辑:mysqli版本使用1:1函数转换,没有安全增强功能,或面向对象的代码:

$con = mysqli_connect($host,$username,$password,$db_name);//these can have defaults as per your php.ini file.

$result = mysqli_query('select * from locations');
$locations = array();
$i=0;
while($row = mysqli_fetch_assoc($result)) {
    $locations['location_'.$i] = $row;
    $i++;
}    
echo json_encode($locations);

答案 2 :(得分:1)

Behseini就是这样做的,

$result = mysql_query('select * from locations');

$locations = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
    $loc["id"] = $row["id"];
    $loc["type"] = $row["type"];
    $loc["lat"] = $row["lat"];
    $loc["long"] = $row["long"];
    $loc["latlong"] = $row["latlong"];

    array_push($locations,$loc);
}