在json_encode中使用foreach

时间:2014-05-26 05:44:15

标签: php mysql json

所以我使用json_encode从MySQL数据库中获取数据。获取数据工作正常但我在foreach循环语句中循环查询时遇到问题。

这是我的代码:

<?php
session_start();
include '../../dbconnect.php';
foreach($_SESSION['sonum'] as $value)
{
    //echo $value;
$rs = mysql_query("select products.product_name as 'product_name', products.product_desc as 'product_desc', order_details.srp as 'srp', order_details.quantity as 'quantity', order_details.commrate as 'comm', order_details.ma as 'ma', order_details.od_no as 'od_no', `sales-order`.`so-no` as 'sono' from products inner join order_details on products.product_id = order_details.product_id inner join `sales-order` on order_details.so_number = `sales-order`.`so-number` where order_details.so_number = '$value' and `po_number` = ''");

$result = array();

while($row = mysql_fetch_object($rs)){
    array_push($result, $row);
}

echo json_encode($result);
}
?>

这里的结果不起作用:

[{"product_name":"3C3CRBSG28PWR93","product_desc":"3Com 3CRBSG28PWR93 Baseline Plus Switch 2928 HP V1910-24G-PoE (170W)\r\n","srp":"56000.00","quantity":"2","comm":"0.010","ma":"0.00","od_no":"30","sono":"ASDie"},{"product_name":"BRODCP-1510","product_desc":"Brother DCP-1510 Printer","srp":"68000.00","quantity":"2","comm":"0.010","ma":"0.00","od_no":"31","sono":"ASDie"}][{"product_name":"Intel DC","product_desc":"Intel Pentium Quad Core ","srp":"0.00","quantity":"0","comm":"0.000","ma":"0.00","od_no":"34","sono":"ry46"},{"product_name":"HP Pavillion TS 14-n039TU","product_desc":"3rd generation intel Core 13-3217u","srp":"0.00","quantity":"0","comm":"0.000","ma":"0.00","od_no":"35","sono":"ry46"}][{"product_name":"Intel DC","product_desc":"Intel Pentium Quad Core ","srp":"0.00","quantity":"0","comm":"0.000","ma":"0.00","od_no":"42","sono":"asdaewe"},{"product_name":"HP Pavillion TS 14-n039TU","product_desc":"3rd generation intel Core 13-3217u","srp":"0.00","quantity":"0","comm":"0.000","ma":"0.00","od_no":"43","sono":"asdaewe"}]

我不确定自己做错了什么,这对我来说是一个很好的帮助。

1 个答案:

答案 0 :(得分:1)

将一些陈述从循环中删除:

<?php
session_start();
include '../../dbconnect.php';

$result = array();

foreach($_SESSION['sonum'] as $value) {
    //echo $value;
    $rs = mysql_query("select products.product_name as 'product_name', products.product_desc as 'product_desc', order_details.srp as 'srp', order_details.quantity as 'quantity', order_details.commrate as 'comm', order_details.ma as 'ma', order_details.od_no as 'od_no', `sales-order`.`so-no` as 'sono' from products inner join order_details on products.product_id = order_details.product_id inner join `sales-order` on order_details.so_number = `sales-order`.`so-number` where order_details.so_number = '$value' and `po_number` = ''");

    while($row = mysql_fetch_object($rs)){
        $result[] = $row;
    }
}

echo json_encode($result);
?>

在循环之前,我已将$result声明为数组。您遇到的问题是$result在每次迭代中被重新声明为空数组。

此外,json_encode函数位于循环之后,因为您只需要在将所有元素推入数组后对其进行编码。

另一个性能改进是在向数组添加一个元素时使用方括号表示法而不是array_push,因此$result[] = $row