Aaron Alfonso Aaron Alfonso - 5 months ago 8
JSON Question

PHP JSON Encode: Formatting

I wanted to have an json output format like this

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

]

}


However, it is showing differently as wanted. The first items keeps on replicated.
The result is:

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

]

}


This is my php code:

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

Answer

$new_row is not cleared, so it holds the data of the previous iteration. So, change your foreach to:

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
}
Comments