Excluding numbered-index elements of PDO::fetchAll()

社会主义新天地 提交于 2020-07-30 07:54:28

问题


$allrows = $pdo->fetchAll(); // select * from ....

I want to transform this $allrows into JSON by doing :

echo (json_encode($allrowl,JSON_PRETTY_PRINT));

My problem is that this fetchAll will not only extracting data as associate array but also indexed array for each element, hence repeating elements.

[
    {
        "org_id": "1",
        "0": "1",
        "category": "A",
        "1": "A",

    },
    {
        "org_id": "2",
        "0": "2",
        "category": "A",
        "1": "A",

    }
]

Thank you.


回答1:


That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.

Assuming $pdo is a PDOStatement, set it like this prior to the fetch.

   $pdo->setFetchMode(PDO::FETCH_ASSOC);

You can also set it in the fetch statement:

   $pdo->fetchAll(PDO::FETCH_ASSOC);



回答2:


Use PDO::FETCH_ASSOC to get only the associated arrays:

$allrows = $pdo->fetchAll(PDO::FETCH_ASSOC);


来源:https://stackoverflow.com/questions/37968968/excluding-numbered-index-elements-of-pdofetchall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!