2

I am wondering if this is possible.

I have a table with three columns (there's an id column too, but irrelevant here):

[year] [month] [price]

How do I generate an array that consolidates year and month?

Result would be like this:

[
2011 => [Jan => price, Feb => price, etc.]
2012 [Jan => price, Feb => price, etc.]
]

Any way to this directly with PDO, instead of looping and creating it with PHP?

I've tried the FETCH GROUP fetch mode, but haven't been successful.

0

2 Answers 2

1

You will have to loop over the structure, the only methods to retrieve data from the PDO results are the following

  • PDOStatement::fetch
  • PDOStatement::fetchAll
  • PDOStatement::fetchColumn
  • PDOStatement::fetchObject

None of these return in multi-dimensional arrays.

IMO here is the simplest way to acheive this:

$db = new PDO(...);

$query = $db->query("
    SELECT 
        year, month, SUM(price) AS total_price
    FROM 
        table
    GROUP BY 
        year, month
");

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

$results = array();
while ($row = $query->fetch()) {
    list($year, $month, $totalPrice) = $row;

    if (!isset($results[$year])) {
        $results[$year] = array();
    } //if

    $results[$year][$month] = $totalPrice;

} //while

unset($query);
unset($db);
1
  • 2
    Why was this downvoted... he asked if it was possible. It is not possible with PDO. Commented Apr 18, 2014 at 16:00
-1

The best I could come up with is

http://www.sqlfiddle.com/#!2/a87785/10/0

SELECT a.year, 
   Group_concat(a.arr) 
FROM   (SELECT year, 
           (SELECT Concat(sub.month, ' ', Group_concat(price)) 
            FROM   test sub 
            WHERE  sub.year = t.year 
                   AND sub.month = t.month 
            GROUP  BY month) AS arr 
    FROM   test t 
    GROUP  BY year, 
              month) a 
GROUP  BY a.year; 

but this implies to explode afterwards. I am pretty sure multidimensional arrays aren't supported by the current implementations of PDO

1
  • This will only work with MySQL CONCAT and Group_concat is not part of all SQL so will not work with all PDO drivers. Commented Apr 18, 2014 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.