我通过pdo从我的mySQL数据库获取数据:
$people = $db->query('SELECT * FROM people ORDER BY id ASC;')->fetchAll(PDO::FETCH_UNIQUE);
数组people
如下所示:
array(84) {
[40]=>
array(12) {
["name"]=>string(5) "Tiger Nixon"
[0]=> string(5) "Tiger Nixon"
["positon"]=> string(7) "System Architect"
[1]=> string(7) "System Architect"
["salary"]=> string(10) "$320,800"
[2]=> string(10) "$320,800"
["start_date"]=> string(11) "2011/04/25"
[3]=> string(11) "2011/04/25"
["office"]=> string(5) "Edinburgh"
[4]=> string(5) "Edinburgh"
["extn"]=> string(5) "5421"
[5]=> string(5) "5421"
}
[41]=>
array(12) {
["name"]=> string(5) "Garrett Winters"
[0]=> string(5) "Garrett Winters"
["positon"]=> string(7) "Accountant"
[1]=> string(7) "Accountant"
["salary"]=> string(10) "$170,750"
[2]=> string(10) "$170,750"
["start_date"]=> string(11) "2011/07/25"
[3]=> string(11) "2011/07/25"
["office"]=> string(5) "Tokyo"
[4]=> string(5) "Tokyo"
["extn"]=> string(5) "8422"
[5]=> string(5) "8422"
}
...
如果我现在通过echo json_encode($people);
结果是:
{"40":{
"name":"Tiger Nixon",
"0":"Tiger Nixon",
"position":"System Architect",
"1":"System Architect",
"salary":"$320,800",
"2":"$320,800",
"start_date":"2011/04/25",
"3":"2011/04/25",
"office":"Edinburgh",
"4":"Edinburgh",
"extn":"5421",
"5":"5421",
},
...
但这不是我需要的格式。其实我需要这种格式:
[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
},
...
]
答案 0 :(得分:1)
然后你应该告诉fetchAll()
你想要一个关联数组返回,而不是关联数组和数字数组。
->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)