如何获取按列名索引的数组?

时间:2013-06-07 00:16:44

标签: php jquery mysql json pdo

我有这个:

$pdo = new PDO("mysql:host=$host;dbname=$databaseName;charset=utf8", $user, $pass);
$query = "SELECT name FROM $tableName";
$stm = $pdo->prepare($query);
$stm->execute();
$array = $stm->fetchAll();
$firephp->log($array);
echo json_encode($array);

ajax的结果是:

[{"name":"mike","0":"mike"},{"name":"john","0":"john"},{"name":"tito","0":"tito"}]

但我希望得到这个:

{"name":[{"mike","john","tito"}]}

哪个PDO fetch_style或者我应该在PHP中做什么来接收我想要的jQuery字符串?

非常感谢。

2 个答案:

答案 0 :(得分:1)

$array = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode(array('name' => $array));

答案 1 :(得分:0)

您可以使用PDO获取列名:

$col_count = $stmt->columnCount();
$col_names = array();
for ($col = 0; $col < $col_count; $col++) {
    $col_names[] = $stmt->getColumnMeta($col)['name'];
}