Search code examples
phpmysqlfetchallpdo

How to fetch data using PDO in the format [col1=>[col2=>col3,col2=>col3]]?


I have a MySQL table called bid_lvl_descs with columns bid_type, lvl, desc

Bid_type and lvl together are always unique, and desc for the purposes will be, but technically can be not unique. Example data:

+----------+-----+---------------------+
| bid_type | lvl |        desc         |
+----------+-----+---------------------+
|        9 |   1 |  Blabla             |
|        9 |   2 |  bla ba bla         |
|        9 |   3 |  bla bla bla bla    |
|        9 |   4 |  Bllsllsabablalllll |
|        7 |   1 |  bla                |
|        7 |   2 |  blabla             |
|        7 |   3 |  blablabla          |
|        7 |   4 |  Bbllaallssl        |
+----------+-----+---------------------+

I want to select the data and save it in PHP array so I could easily access and cache if needed by doing simple cached_arr[ bid_type ] [ lvl ]

array {
          9 array {
1 => 'bla',
2 => 'blabla', 
3 => 'blablabla',
4 => 'blablablabla'
}
         7 array {
1=> ...
2=>
3=>
4=>... 
}
//An so on
}

I tried PDOStatement::fetchAll(PDO::FETCH_GROUP), but it creates array of slightly more complicated format than neccesary. Any tips?

Code:

<?php
echo var_dump($db->run('SELECT bid_type,lvl,desc FROM bid_lvl_descs')->fetchAll(PDO::FETCH_GROUP);

Gives the following array:

Array {
9 array {
0 array {
'lvl'=>1,
'desc'=>'bla'
}
}
7 array {
0 array {
desc => 'bla'
lvl=1
}
// ... And so on
}
}

Solution

  • You can do this with PHP:

    $results = $db->run('SELECT bid_type,lvl,desc FROM bid_lvl_descs')->fetchAll();
    $output = [];
    foreach($results as $result){
        $output[$result['bid_type']][] = $result;
    }