Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, it's not possible to get an array within an array as the result directly from a relational (SQL) database.</p> <p>You'll need to loop over the results and create the array yourself, e.g.</p> <pre><code>$productsById = array(); foreach ($dbRows as $row) { if (!isset( $productsById[$row['product_id']] )) { $product = array( 'id' =&gt; $row['product_id'], 'name' =&gt; $row['product_name'] ); //note the use of the &amp; to set the $product array by reference $productsById[$row['product_id']] = &amp;$product; } //note the use of the &amp; to retrieve the $product array by reference else $product = &amp;$productsById[$row['product_id']]; $product['images'][] = array( 'id' =&gt; $row['image_id'] ); //We unset this because we accessed it by reference above; this prevents referencing the wrong product //on the next iteration of the loop. unset($product); } </code></pre> <p>Or, to get an array of objects:</p> <pre><code>$productsById = array(); foreach ($dbRows as $row) { if (!isset( $productsById[$row['product_id']] )) { $product = new stdClass; $product-&gt;id = $row['product_id']; $product-&gt;name = $row['product_name']; $product-&gt;images = array(); $productsById[$row['product_id']] = $product; } else $product = $productsById[$row['product_id']]; $image = new stdClass; $image-&gt;id = $row['image_id']; $product-&gt;images[] = $image; } </code></pre> <p>It's also worth mentioning, however, that if you're using MySQL (and database portability isn't a concern), you can make use of the GROUP_CONCAT function, e.g.:</p> <pre><code>SELECT p.id as product_id, p.name as product_name, GROUP_CONCAT(i.id) as image_ids FROM product p LEFT JOIN image i ON p.id = i.product_id GROUP BY p.id </code></pre> <p>Then in your PHP, you'd have only one $row array for each product, and you could get the image IDs simply by using:</p> <pre><code>$imageIds = explode(',', $row['image_ids']); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload