doutu6658
2013-06-07 00:16
浏览 195

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

I have this:

$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);

Result on ajax is:

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

But i want to get this:

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

Which PDO fetch_style or what should i do in PHP to receive the string i want on jQuery?

Many thanks.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanluan3651 2013-06-11 14:25
    已采纳
    $array = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
    echo json_encode(array('name' => $array));
    
    打赏 评论
  • dra8603 2013-06-07 00:56

    You can get the column names using PDO:

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

相关推荐 更多相似问题