0

我想遍历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]);
        }
    }
}
4

1 回答 1

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
于 2013-03-19T15:54:42.093 回答