5

My PDO query of the database returns unnecessary values into the array.

Array
(
    [contentID] => 9
    [0] => 9
    [type] => operations
    [1] => operations
    [type_alts] => pages
    [2] => pages
    [url] => ctt-partners
    [3] => ctt-partners
    [title] => CTT Partners
    [4] => CTT Partners
    [subtitle] => 
    [5] => 
    [online] => 1
    [6] => 1
    [access] => 0
    [7] => 0
    [req] => 0
    [8] => 0

)

I am after the array not returning the identical integer fields as well as the names. For example [0] => 9, [1] => operations. I don't want these as well.

Why are they here and how can I get rid of them.

Thanks,

4

4 回答 4

7

您当前的提取类型必须是:

PDO::FETCH_BOTH(默认):返回一个由列名和 0 索引列号索引的数组,如结果集中返回的那样

而根据您的要求,它应该是:

PDO::FETCH_ASSOC: 返回一个按列名索引的数组,如结果集中返回的那样

fetch_style

控制如何将下一行返回给调用者。此值必须是 PDO::FETCH_* 常量之一,默认为 PDO::ATTR_DEFAULT_FETCH_MODE 的值(默认为 PDO::FETCH_BOTH)。

参考:

于 2013-10-27T11:40:49.093 回答
2

因此,只需强制 PDO 执行此操作...

try {
    $pdo = new PDO(...);
    $pdo->query('SELECT * FROM foo');

    foreach ($pdo->query('SELECT * FROM foo', PDO::FETCH_ASSOC) as $row) {
        ...
    }
} catch (PDOException $e) {
    // error handling
}

看看不同的 PDO 获取模式。 http://www.php.net/manual/en/pdostatement.setfetchmode.php

于 2013-10-27T11:42:43.960 回答
1

查看PDOStatement::fetch()的文档:

第一个参数定义如何将下一行返回给调用者。有可用的预定义常量:

◦ PDO::FETCH_ASSOC:返回一个按列名索引的数组,如结果集中返回的那样

◦ PDO::FETCH_BOTH(默认):返回由列名和 0 索引列号索引的数组,如结果集中返回的那样

...
http://www.php.net/manual/pdostatement.fetch.php

您可能使用FETCH_BOTH或不使用任何默认为FETCH_BOTH.

将获取类型更改为FETCH_ASSOC.

于 2013-10-27T11:40:56.923 回答
0

我更喜欢使用它,因为我需要它返回一个 JSON 文件:

 $conn = new PDO("...","...","...");
 $stmt = $conn->prepare($query);
 $stmt->execute();
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
于 2018-08-31T03:55:46.023 回答