NotionCommotion Posted December 5, 2014 Share Posted December 5, 2014 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 More sharing options...
Barand Posted December 5, 2014 Share Posted December 5, 2014 while (list($a, $b, $c) = $result->fetch_row()) { $data[$a][$b][] = $c; } Link to comment https://forums.phpfreaks.com/topic/292921-query-table-and-return-sub-arrays/#findComment-1498671 Share on other sites More sharing options...
NotionCommotion Posted December 6, 2014 Author Share Posted December 6, 2014 Thanks Barand, but wouldn't this return: Array ( [1] => Array ( [2] => Array ( [0] => 4 [1] => 5 [2] => 8 ) ) ) where I was looking for: Array ( [a] => 1 => 2 [c] => Array ( [0] => 4 [1] => 5 [2] => 8 ) ) Link to comment https://forums.phpfreaks.com/topic/292921-query-table-and-return-sub-arrays/#findComment-1498693 Share on other sites More sharing options...
Barand Posted December 6, 2014 Share Posted December 6, 2014 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); } } Link to comment https://forums.phpfreaks.com/topic/292921-query-table-and-return-sub-arrays/#findComment-1498718 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.