[英]PHP foreach loop to create JSON from mysql
I have a many to one problem, I have data organized in mysql like:我有一个多对一的问题,我在 mysql 中组织了数据,例如:
>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)我想创建类似于(出于解释目的)的 JSON
>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
function name is not correct mysqli_query
函数名不正确itemed
is wrapped in double array while not needed for that. itemed
包裹在双数组中,但不需要。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.