5less
5less

Reputation: 970

Need help constructing json with PHP

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.

Upvotes: 0

Views: 39

Answers (2)

MacGyer
MacGyer

Reputation: 198

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

Upvotes: 3

Lipsyor
Lipsyor

Reputation: 438

Consider this:

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

I n this way you never overwrite previous data

Upvotes: 1

Related Questions