PHP foreach循环从MySQL创建JSON [英] PHP foreach loop to create JSON from mysql

查看:160
本文介绍了PHP foreach循环从MySQL创建JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多对一的问题,我在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    

我想创建类似JSON(出于解释目的)

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.

  • 从结果集中获取索引的不正确方法
  • mysqli_query函数名称不正确
  • itemed被包装在双数组中,但不需要.
  • 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.

这里是更新的代码.

$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);

这篇关于PHP foreach循环从MySQL创建JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆