note 126195 added to pdostatement.fetchall
| From: | php at erikthiart dot com | Date: | Fri, 25 Jun 2021 11:21:01 +0000 |
| Subject: | note 126195 added to pdostatement.fetchall | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216548@lists.php.net to get a copy of this message | ||
I am adding this here as I donât seem to find any clear and easy to find examples and
explanations of PDO::FETCH_GROUP and how it works by means of an example.
I find this to be one of the most useful modes available in fetchAll() when you need to work with
any form of grouping.
In essence, PDO can group results into nested arrays, based on the first field selected.
Example
<?php
$data = $pdo->query('SELECT sex, name, car FROM users')->fetchAll(PDO::FETCH_GROUP);
/* array (
'male' => array ( 0 =>
array (
'name' => 'John',
'car' => 'Toyota',
),
1 => array (
'name' => 'Mike',
'car' => 'Ford',
),
),
'female' => array (
0 => array (
'name' => 'Mary',
'car' => 'Mazda',
),
1 => array (
'name' => 'Kathy',
'car' => 'Mazda',
),
),
) */
?>
Tip: If you need to group the data by something other than the first field then you can do it like
this as well
<?php
SELECT sex, users.* FROM users
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 102.165.228.177)
----
Manual Page -- https://php.net/manual/en/pdostatement.fetchall.php
Edit -- https://main.php.net/note/edit/126195
Del: integrated -- https://main.php.net/note/delete/126195/integrated
Del: useless -- https://main.php.net/note/delete/126195/useless
Del: bad code -- https://main.php.net/note/delete/126195/bad+code
Del: spam -- https://main.php.net/note/delete/126195/spam
Del: non-english -- https://main.php.net/note/delete/126195/non-english
Del: in docs -- https://main.php.net/note/delete/126195/in+docs
Del: other reasons-- https://main.php.net/note/delete/126195
Reject -- https://main.php.net/note/reject/126195
Search -- https://main.php.net/manage/user-notes.php