Jump to content

Query table and return sub-arrays


NotionCommotion

Recommended Posts

Given the following query,

SELECT t1.a, t1.b, t2.c FROM t1 INNER JOIN t2 ON t2.id=t1.t2_id WHERE t1.pk=123;

I get the following three records:

array(
  array('a'=>1,'b'=>2,'c'=>4),
  array('a'=>1,'b'=>2,'c'=>5),
  array('a'=>1,'b'=>2,'c'=>
)

What would be the best way to get just one record such as the following?

array('a'=>1,'b'=>2, 'c'=>array(4,5,)

My thoughts were to use MySQL's GROUP_CONCAT, and then use implode() to turn it into an array, but didn't know if there was a better way.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/292921-query-table-and-return-sub-arrays/
Share on other sites

Yes - Step 1 = get array "c" for unique combinations of a and b

while (list($a, $b, $c) = $result->fetch_row()) {
    $data[$a][$b][] = $c;
}

// STEP 2
foreach ($data as $a => $adata) {
    foreach ($adata as $b => $c) {
        $result[] = array('a' => $a, 'b' => $b, 'c' => $c);
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.