我在 json
方法中从 MySQL 数据库中检索和打印数据:
$ret = array();
$fileName = Access::FetchDB("SELECT name FROM tags");
$ret[]= $fileName;
echo json_encode($ret);
现在的输出是:
[[{"name":"test1"},{"name":"test2"},{"name":"test3"}]]
但我需要这个输出:
["test1","test2","test3"]
我如何打印这个?
最佳答案
[[{"name":"test1"},{"name":"test2"},{"name":"test3"}]]
就像拥有这个
array(array(array('name' => 'test1'), array('name' => 'test2'), array('name' => 'test3')));
首先,不要这样做:
$ret[]= $fileName;
只保留 $fileName
应该是这样的:
array(array('name' => 'test1'), array('name' => 'test2'), array('name' => 'test3'));
更好的做法是使用 array('test1', 'test2', 'test3')
并在不使用 array_values() 的情况下对其进行编码。你可以在 php 端做到这一点:
$ret = array();
$fileName = Access::FetchDB("SELECT name FROM tags");
foreach($fileName as $key => $value)
$ret[] = $value['name'];
echo json_encode($ret);
关于PHP MySQL JSON 自定义输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340703/