Jump to content

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);
    }
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.