-1

我正在尝试使用 json_encode 将一些数据回显到我的 ajax 调用,但我似乎只接收到一部分数据,特别是最后一条记录。在下面的查询中,当我$q->num_rows();正确返回正确的行数时,6。但是,当我查看生成的 JSON 对象时,我看到它只有第 6 行的最后一对值。第 1 行的数据-5 无处可寻。

谁能看到我可能做错了什么?谢谢。

function myAjaxFunction(){
    $muni = $this->input->POST('muni');
    $q = $this->db->query("SELECT SaleYear AS Y, NewSaleType AS T, count(*) AS C, format((sum(SalePrice) / sum(Quantity1)),0) AS R FROM tblsales WHERE  tblsales.SaleYear > 2007 AND tblsales.Quantity1 > 2000 AND (tblsales.NewSaleType = 'Industrial') AND tblsales.Municipality = '".$muni."' GROUP BY T,Y ORDER BY T,Y");
    $json_SaleYear = array();
    $json_AvrgRate = array();
    foreach ($q->result_array() as $row){
        $json_SaleYear = $row['Y'];
        $json_AvrgRate = $row['R'];
    }
    $json['Y'] = $json_SaleYear;
    $json['R'] = $json_AvrgRate;            
    echo json_encode($json);
    exit;
}
4

4 回答 4

2

您已将$json_SaleYearand声明$json_AvrgRate为数组,但未使用数组索引在foreach循环中定义值,因此它只有一条记录,即最后一条记录..

仅更改您的部分代码

foreach ($q->result_array() as $row){
        $json_SaleYear[] = $row['Y'];
        $json_AvrgRate[] = $row['R'];
    }
于 2013-09-26T05:02:24.020 回答
1

您正在用foreach循环中的值替换数组,而不是附加到数组中。因此,在循环的每次迭代中,$json_SaleYear/AvrgRate变量都会被当前行的信息覆盖。循环完成后,它们仅包含最后一行的信息。

而不是像这样更新变量,

foreach ($q->result_array() as $row){
    $json_SaleYear = $row['Y'];
    $json_AvrgRate = $row['R'];
}

你应该像这样附加到数组中,

foreach ($q->result_array() as $row){
    $json_SaleYear[] = $row['Y']; // Note the []'s.
    $json_AvrgRate[] = $row['R'];
}
于 2013-09-26T05:01:25.817 回答
1

替换以下

$json_SaleYear = array();
$json_AvrgRate = array();
foreach ($q->result_array() as $row){
    $json_SaleYear = $row['Y'];
    $json_AvrgRate = $row['R'];
}
$json['Y'] = $json_SaleYear;
$json['R'] = $json_AvrgRate;
echo json_encode($json);

和:

$json = array( 
    'Y' => array(),
    'R' = array()
);
foreach ($q->result_array() as $row){
    $json['Y'][] = $row['Y'];
    $json['R'][] = $row['R'];
}
echo json_encode($json);
于 2013-09-26T05:06:00.180 回答
-1

尽管您已将 $json_SaleYear 和 $json_AvrgRate 声明为数组,但您将其值设置为字符串。正确的格式如下

function myAjaxFunction(){
    $muni = $this->input->POST('muni');
    $q = $this->db->query("SELECT SaleYear AS Y, NewSaleType AS T, count(*) AS C, format((sum(SalePrice) / sum(Quantity1)),0) AS R FROM tblsales WHERE  tblsales.SaleYear > 2007 AND tblsales.Quantity1 > 2000 AND (tblsales.NewSaleType = 'Industrial') AND tblsales.Municipality = '".$muni."' GROUP BY T,Y ORDER BY T,Y");
    $json_SaleYear = array();
    $json_AvrgRate = array();
    $counter = 0;
    foreach ($q->result_array() as $row){
      $json_SaleYear[$counter] = $row['Y'];
      $json_AvrgRate[$counter] = $row['R'];
      $counter++;
    }
    $json['Y'] = $json_SaleYear;
    $json['R'] = $json_AvrgRate;            
    echo json_encode($json);
   exit;
}
于 2013-09-26T05:03:35.023 回答