简体   繁体   中英

PHP foreach loop to create JSON from mysql

I have a many to one problem, I have data organized in mysql like:

>order1 : mycustomer : item1    
>order1 : mycustomer : item2    
>order2 : mycustomer : item3    
>order2 : mycustomer : item1    
>order3 : mycustomer : item2    

I want to create the JSON something like (for explanation purposes)

>order1 mycustomer    
>> item1    
>> item2,

>order2 mycustomer  
>> item3    
>> item1,    

>order3 mycustomer    
>> item2

But my looping is not correct, I am not getting the order with item array then repeat for next order. What am I doing wrong.

$query = "SELECT * from `orders` WHERE proc = 'N'";
$result = $conn->query($query);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    $onum = $row['order_number'];

    foreach($result as $results)
    {
        $quantity_invoiced = $row[quantity_invoiced];
        $unit_price = $row[unit_price];
        $item_description = $row['item_description'];

        $itemed = $results['item_description'];
        echo $itemed;
      $tx_data[] = [
      "partnerRef" => $onum,
      "lines" => $itemed
      ];
    }


}
$flagupdate = "UPDATE `orders` SET proc = 'Y' where proc = 'N'";
myqueryi_query($conn, $flagupdate);

} else {
echo "no results";
}

echo json_encode($tx_data);

There are few syntax errors and also typo mistake in function names.

  • Not a proper way to getting indexes from result-set
  • mysqli_query function name is not correct
  • itemed is wrapped in double array while not needed for that.

Here is updated code.

$query = "SELECT * from `orders` WHERE proc = 'N'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $onum = $row['order_number'];
        $socust = $row['salesorder_cust'];

        foreach($result as $results){
            $quantity_invoiced = $row['quantity_invoiced'];
            $unit_price = $row['unit_price'];
            $item_description = $row['item_description'];
            $itemed = $results['item_description'];
            echo $itemed;

            $tx_data[] = [
            "tpRef" => $socust,
            "partnerRef" => $onum,
            "lines" => $itemed
            ];
        }

    }

    $flagupdate = "UPDATE `orders` SET proc = 'Y' where proc = 'N'";
    mysqli_query($conn, $flagupdate);
} else {
    echo "no results";
}
echo json_encode($tx_data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM