我有以下代码:
$db = Frapi_Database::getInstance();
$origin = $this->getParam('origin', self::TYPE_STRING);
$destination = $this->getParam('destination', self::TYPE_STRING);
$stmt = $db->prepare("SELECT DEPARTURE_TIME, TIME FROM TRAVELTIME WHERE ORIGIN = ? AND DESTINATION = ?");
$stmt->execute(array($origin, $destination));
//$time = $stmt->fetchColumn();
$this->data = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($this->data);
然而,这给了我类似的东西:
array(30) {
[0]=>
array(2) {
["DEPARTURE_TIME"]=>
string(5) "12:00"
["TIME"]=>
string(2) "99"
}
[1]=>
array(2) {
["DEPARTURE_TIME"]=>
string(5) "12:15"
["TIME"]=>
string(3) "105"
}
[2]=>
array(2) {
["DEPARTURE_TIME"]=>
string(5) "12:30"
["TIME"]=>
string(3) "115"
}
[3]=>
array(2) {
["DEPARTURE_TIME"]=>
string(5) "12:45"
["TIME"]=>
string(3) "122"
}
}
我不希望它像这种格式,我希望它是:
{"DEPARTURE_TIME":"12:00","TIME":"99"}, {"DEPARTURE_TIME":"12:15","TIME":"123"} and so on
我做了一个json_decode,我得到了:
{"DEPARTURE_TIME":"12:00","0":"12:00","TIME":"99","1":"99"},{"DEPARTURE_TIME":"12:15","0":"12:15","TIME":"105","1":"105"}
不知道为什么会这样
答案 0 :(得分:1)
对于这种情况
print implode(', ', array_map(function($a){
print '{"DEPARTURE_TIME":"'.$a["DEPARTURE_TIME"].'","TIME":"'.$a['TIME'].'"}';
}));
对于所有情况,您都可以使用json_encode
$this->data = $stmt->fetchAll(PDO::FETCH_OBJ); // as I check it's ok to use PDO_FETCH_ASSOC too
json_encode($this->data);