如何从执行的预准备语句创建JSON?

时间:2017-10-25 18:26:56

标签: php sql json

我刚刚编写了一些基本的PHP代码,如下所示:

$pdo = new PDO("mysql:host=localhost;dbname=locationtracker", "xxxx", "xxxx");
$statement = $pdo->prepare("SELECT * FROM waypoints");
$result = $statement->execute();

if ($result){
    echo "Success";
    $resultArray = array();
    $tmpArray = array();

    while($row = $statement->fetch()){
        print_r($row);
        echo "<br>";
        $tmpArray = $row;
        array_push($resultArray, $tmpArray);
    }
    print_r(json_encode($resultArray));
}else{
    die("Error.<br>");
}

sql table&#39; waypoints&#39;看起来像这样:

waypoints
        | x: double
        | y: double
        | name: varchar(255)
        | city: varchar(255)
        | id: Int

所以我想将数组转换为JSON格式。听起来很简单,但是我的PHP代码就像这样产生了:

Success
Array ( [x] => 7.0000 [0] => 7.0000 [y] => 32.0000 [1] => 32.0000 [name] => Georgia [2] => Georgia [city] => Georgia [3] => Georgia [id] => 1 [4] => 1 ) 
Array ( [x] => 5.0000 [0] => 5.0000 [y] => 34.000 [1] => 34.000 [name] => Home [2] => Home [city] => St.Martin [3] => St.Martin [id] => 1 [4] => 1 ) 

[{"x":"7.0000","0":"7.0000","y":"32.0000","1":"32.0000","name":"Georgia","2":"Georgia","city":"Georgia","3":"Georgia","id":"1","4":"1"},{"x":"5.0000","0":"5.0000","y":"34.000","1":"34.000","name":"Home","2":"Home","city":"St.Martin","3":"St.Martin","id":"1","4":"1"}]

这不是我想要的。所有变量现在都是重复的(一次:名称,第二次:索引)。有没有办法只按名称获取变量,因为我不希望每个对象在我的数组和JSON对象中都是两次。

如果您有任何其他问题,请与我们联系。

1 个答案:

答案 0 :(得分:2)

默认情况下,PDO fetch返回以数字和关联方式索引的数组。您只需要关联索引。

while($row = $statement->fetch(PDO::FETCH_ASSOC)){
  //...
}

请参阅https://secure.php.net/manual/en/pdostatement.fetch.php#refsect1-pdostatement.fetch-parameters