Loop and array and sub array I am working on a script that needs to loop an array and loop a sub array. I want to take in rows from a table (that piece works fine) that look like:

invoice | item
inv1    | it_A
inv1    | it_C
inv2    | it_D
inv2    | it_B
inv3    | it_A


and display the JSON (also works) like pseudo code

inv1

   it_C
   it_D

inv2

   it_D
   it_B

inv3

   it_A


but I have the loop wrong, thanks for any assistance

$result = $conn-&gt;query($sql);

if ($result-&gt;num_rows &gt; 0) {

echo "rows found";
    while($row = $result-&gt;fetch_assoc()) {

$invid = $row[invoice_number];
echo $invid;



foreach($invid as $invoicelines)
{

$sql1 = $invoicelines[item_code];



echo $sql1;
Using the SQL will get you the invoice and json aggregated items in an array:

SELECT invoice, JSON_ARRAYAGG(item)
FROM tablename
GROUP BY invoice