question about PDO and formatting output
I have the following code:
$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);
This however gives me something like:
array(30) {
[0]=>
array(2) {
["DEPARTURE_TIME"]=>
string(5) "12:00"
["TIME"]=开发者_如何学JAVA>
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"
}
}
I don't want this to be like this format, I want it to be:
{"DEPARTURE_TIME":"12:00","TIME":"99"}, {"DEPARTURE_TIME":"12:15","TIME":"123"} and so on
I did a json_decode and I got:
{"DEPARTURE_TIME":"12:00","0":"12:00","TIME":"99","1":"99"},{"DEPARTURE_TIME":"12:15","0":"12:15","TIME":"105","1":"105"}
don't know why this is
For this case
print implode(', ', array_map(function($a){
print '{"DEPARTURE_TIME":"'.$a["DEPARTURE_TIME"].'","TIME":"'.$a['TIME'].'"}';
}));
For all cases you can use 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);
精彩评论