简体   繁体   中英

Need to generate a json array of objects from PHP

I have a tested and functioning block of code that reads in a json file and places the information into a table, when the json file is formatted as follows:

[
  {
    "title": "Title One",
    "hits": 99,
    "type": "Type 1",
    "id": "001"
  },
  {
    "title": "Title Two",
    "hits": 109,
    "type": "Type 2",
    "id": "002"
  },
  {
    "title": "Title Three",
    "hits": 119,
    "type": "Type 3",
    "id": "003"
  }
]

This is an array of PHP objects. The issue is I am having trouble dynamically generating this json from my PHP - the above wasn't generated it was just a test file for the front end. The best I've gotten is to generate an array of arrays, which isn't read by my table. The end of my PHP, and the relevant part, is as follows:

do {
    $model[] = array(
                    'plays' => $row_GetTotalItems['Rows'],
                    'title' => $row_GetTotalItems['video_title'],
                    'id' => $row_GetTotalItems['videoID']
    );
 } while ($row_GetTotalItems = mysql_fetch_assoc($GetTotalItems));
}
} 

header("Content-type: application/json");
json_encode($model); 
print_r($model);
?>

Any thoughts on how to properly generate the json file so that it is formatted as my table is looking for it?

Get off mysql_* and move to MySQLi or PDO, but for the issue, fetch objects. You also need to assign the JSON encoded string to something or just echo it. Secondly, don't use do as it will DO even if there is no row fetched the first time or last:

while ($row_GetTotalItems = mysql_fetch_object($GetTotalItems)) {
    $model[] = $row_GetTotalItems;
}
header("Content-type: application/json");
echo json_encode($model); 

For future reference, you can create an array and cast to an object:

$model[] = (object)array('plays' => $row_GetTotalItems['Rows'],
                         'title' => $row_GetTotalItems['video_title'],
                         'id' => $row_GetTotalItems['videoID']
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM