0

I want the following json data created with php. I'am getting the required values from my database.

JSON i want to output(I created it manually to show):

{  
   "room":[  
      {  
         "id":"1",
         "temp":"20"
      },
      {  
         "id":"2",
         "temp":"30"
      }
   ]
}

Current PHP:

 $rows = array();
    if(!$allData->count()) {
        echo 'No results!';
    } else {
        foreach ($allData->results() as $allData) {
            $rows['id'] = $allData->id;
            $rows['data'] = $allData->temp;
        }
    }

// echo out as json data
    echo '{"rom":'.json_encode($rows).'}';

This is what my current PHP script outputs:

{"rom":{"id":"2","data":"20"}}

JSON formatted:

{  
   "rom":{  
      "id":"2",
      "temp":"30"
   }
}

As you can see it outputs only the last id and temp values..

I can't seem to find out what I'am doing wrong, any help is greatly appreciated.

2 Answers 2

3

You are missing one dimension in your array:

$rows = array();
if(!$allData->count()) {
    echo 'No results!';
} else {
    foreach ($allData->results() as $allData) {
        $rows[] = [
           'id' => $allData->id,
           'data' => $allData->temp,
        ];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also, please update do this: $rows[] = [ 'id' => $allData->id, 'data' => $allData->temp ]; You had too many double qoutes in there. Thank you for your help MacGyver!
1

Consider this:

$rows[] = ["id"=>$allData->id, "data"=>$allData->temp];

I n this way you never overwrite previous data

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.