Reputation: 120
suppose i have a simple table like
name | email
a | [email protected]
b | [email protected]
If i do
$result = $db->fetchAll(PDO::FETCH_ASSOC)
on a SELECT * for example, I get something like
Array{
[0] => array{
['name'] => 'a'
['email'] => '[email protected]'
}
[1] => array{
['name'] => 'b'
['email'] => '[email protected]'
}
}
I would want something like
Array{
['name'] => Array{
[0] => 'a'
[1] => 'b'
}
['email'] => Array{
[0] => '[email protected]'
[1] => '[email protected]'
}
}
So that $result['name'] is an array with all the names. I know i can write a very small function to do that myself. Just wondering if there was some fetch_style parameter that would do that automatically. Thanks!
Upvotes: 0
Views: 1300
Reputation: 70
There is one way to do that.
You can use PDO::FETCH_GROUP
as suggested here:
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
This flag will index by first column of your select, you only have to move your wanted indexed field to position 0.
Upvotes: 1
Reputation: 2348
There's no way to do it with any PDO flags.
Here' my suggested converting script, it's very small:
$result = [];
foreach($array as $arr) foreach($arr as $k=>$v) $result[$k][] = $v;
print_r($result);
Upvotes: 2