Aaron Alfonso
Aaron Alfonso

Reputation: 516

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

Upvotes: 1

Views: 42

Answers (2)

kiran gadhvi
kiran gadhvi

Reputation: 228

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

Upvotes: 1

Thamilhan
Thamilhan

Reputation: 13303

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

Upvotes: 4

Related Questions