echo JSON_ENCODE($ json)仅包含最后一条记录的数据

时间:2013-09-26 04:58:21

标签: php ajax json

我正在尝试使用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 个答案:

答案 0 :(得分:2)

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

只更改部分代码

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

答案 1 :(得分: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'];
}

答案 2 :(得分: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);

答案 3 :(得分:-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;
}