score:2

Accepted answer
SELECT
    company, 
    GROUP_CONCAT(value SEPARATOR ',') AS value, 
    GROUP_CONCAT(monthyear SEPARATOR ',') AS monthyear
FROM
    yourTable
GROUP BY
    company

Some Reference for GROUP_CONCAT.

PHP solution:

Select the to be grouped attribute sorted (company). Loop over them and open a new group every time you encounter a different value for company. As long as the current row has the same row as the previous, add value and monthyear to the current company.

You could do this even without sorting:

while($row = mysql_fetch_assoc($resource))
{
    $values[$row["country"]][] = $row["value"];
    $monthyear[$row["country"]][] = $row["monthyear"];
}

Some output example

foreach ($values as $country => $valuesOneCountry)
{
    // each country
    var_dump($country);

    foreach ($valuesOneCountry as $i => $value)
    {
        // value, monthyear for each original row

        var_dump($value, $monthyear[$country][$i]);
    }
}

Elegant way with OOP:

class Tuple
{
    public $country, $values, $monthyears;

    public function __construct($country, $values = array(), $monthyears = array())
    {
        $this->country = $country;
        $this->values = $value;
        $this->monthyears = $monthyears;
    }
}

$tuples = array();
while($row = mysql_fetch_assoc($resource))
{
    if (!isset($tuples[$row["country"]]))
         $tuples[$row["country"]] = new Tuple($row["country"]);

    // save reference for easy access        
    $tuple = $tuples[$row["country"]];

    // or some method like $tuple->addValue($row["value"]);
    $tuple->values[] = $row["value"];
    $tuple->monthyears[] = $row["monthyear"];
}

var_dump($tuples);

Related Articles