使用 PDO::FETCH_COLUMN 和 PDO::FETCH_GROUP 时要小心。默认情况下,结果按第一列(索引 0)分组,并返回第二列(索引 1)。但是,如果您提供获取参数,它不会影响返回的列,而是影响分组列。如果显式设置分组列,则返回第一列而不是第二列。
<?php
$insert = $dbh->prepare("INSERT INTO people(id, gender) VALUES (?, ?)");
$insert->execute(array('2', 'female'));
$insert->execute(array('3', 'female'));
$insert->execute(array('4', 'female'));
$insert->execute(array('5', 'male'));
$insert->execute(array('6', 'male'));
$sth = $dbh->prepare("SELECT gender, id FROM people");
$sth->execute();
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>
返回
<?php
array (size=2)
'female' =>
array (size=3)
0 => string '2' (length=1)
1 => string '3' (length=1)
2 => string '4' (length=1)
'male' =>
array (size=2)
0 => string '5' (length=1)
1 => string '6' (length=1)
?>
但是,
<?php
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, 0));
?>
返回
<?php
array (size=2)
'female' =>
array (size=3)
0 => string 'female' (length=1)
1 => string 'female' (length=1)
2 => string 'female' (length=1)
'male' =>
array (size=2)
0 => string 'male' (length=1)
1 => string 'male' (length=1)
?>
<?php
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, 1));
?>
返回
<?php
array (size=5)
2 =>
array (size=1)
0 => string 'female' (length=1)
3 =>
array (size=1)
0 => string 'female' (length=1)
4 =>
array (size=1)
0 => string 'female' (length=1)
5 =>
array (size=1)
0 => string 'male' (length=1)
6 =>
array (size=1)
0 => string 'male' (length=1)
?>
返回第一列,并按提供的列索引进行分组。