Doctrine DBAL:如何获取非整数数组键

时间:2012-12-26 17:45:08

标签: php doctrine

我想循环Doctrine DBAL返回的结果,只返回每个数组的字符串/非整数键。使用下面的代码,Doctrine返回两个字符串键(映射到数据库列名)和由整数键控的重复值。如何使用迭代方法并仅检索字符串/非整数键?

$stmt = $app['db']->prepare('SELECT * FROM table');
$stmt->execute();

while ($row = $stmt->fetch()) {
    print_r($row['track_name']);
}

返回

Array
(
    [field1] => foo1
    [0] => foo1
    [field2] => bar1
    [1] => bar1
)
Array
(
    [field1] => foo2
    [0] => foo2
    [field2] => bar2
    [1] => bar2
)
...

我想得到

Array
(
    [field1] => foo1
    [field2] => bar1
)
Array
(
    [field1] => foo2
    [field2] => bar2
)
...

无需诉诸

$fields = array('field1', 'field2');
while ($row = $stmt->fetch()) {
    foreach ($row as $key => $val) {
        if (in_array($key, $fields)) {
            print_r($row[$key]);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

更改行

while ($row = $stmt->fetch()) {

while ($row = $stmt->fetch(\Doctrine\ORM\Query::HYDRATE_ARRAY)) {

您也可以使用PDO:FETCH_ASSOC(似乎是Doctrine使用相同的常量值)。其他有效值为:

  • HYDRATE_OBJECT
  • HYDRATE_SCALAR
  • HYDRATE_SINGLE_SCALAR
  • HYDRATE_SIMPLEOBJECT