1

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
0

2 Answers 2

4

$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
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.