PHP JSON编码:格式化

时间:2016-06-06 10:33:23

标签: php json

我想拥有像这样的json输出格式

{
    "data":
    [
        ["FAMILY: Isopropyl Alcohol 250ml","32.34"],
        ["AMBROXOL Expel 6mg-mL 15ML Drops","75.04"]

    ]

}

然而,它显示出不同的需要。第一项继续复制。 结果是:

{
"data":
[
    ["FAMILY: Isopropyl Alcohol 250ml","32.34"],
    ["FAMILY: Isopropyl Alcohol 250ml","32.34","AMBROXOL Expel 6mg-mL 15ML Drops","75.04"]

]

}

这是我的PHP代码:

foreach ($this->cases_model->test() as $row)        {

                $new_row[]=$row['name'];
                $new_row[]=$row['dp'];
                $row_set['data'][] = $new_row; //build an array
          }

      echo json_encode($row_set); //format the array into json data

2 个答案:

答案 0 :(得分:4)

$new_row未清除,因此它保存上一次迭代的数据。因此,请将foreach更改为:

foreach ($this->cases_model->test() as $row){
    $new_row = []; //Reset the array for every loop
    $new_row[]=$row['name'];
    $new_row[]=$row['dp'];
    $row_set['data'][] = $new_row; //build an array
}

答案 1 :(得分:1)

foreach ($this->cases_model->test() as $row)        {

    $new_row[]=$row['name'];
    $new_row[]=$row['dp'];
    $row_set['data'][] = $new_row; //build an array
    $new_row = NULL;     
}