问题
I looked at this tutorial
and tried to create my own php side script to generate json data.
However, I failed on creating a multi-level array.
In the example, a json result of
{
"nextId": null,
"items": [{
"title": "Docker, the Linux container runtime: now open-source",
"url": "http://docker.io",
"id": 5445387,
"commentCount": 39,
"points": 146,
"postedAgo": "2 hours ago",
"postedBy": "shykes"
}, {
"title": "What\u0027s Actually Wrong with Yahoo\u0027s Purchase of Summly",
"url": "http://hackingdistributed.com/2013/03/26/summly/",
"id": 5445159,
"commentCount": 99,
"points": 133,
"postedAgo": "2 hours ago",
"postedBy": "hoonose"
},
],
"version": "1.0",
"cachedOnUTC": "\/Date(1364333188244)\/"
}
was generated, I could use $resultJSON= json_encode($resultArray);
to generate the inner level, which is title, url, id and such, but not 'items' object. I want to know, whether the items
object comes from the table's name or it is created by encoding a generated array data from an array?
I use data encoded as json from this php file:
$query = "SELECT user_id, username, legacy_id, date_created
FROM eq_user";
$result = mysqli_query($connection, $query);
$numRows = mysqli_num_rows($result);
$resultArray = mysqli_fetch_assoc($result);
$resultJSON= json_encode($resultArray);
echo $resultJSON;
The emberjs app will be like
App.Item.reopenClass({
all: function() {
return $.getJSON("/get_data.php").then(function(response) {
var items = [];
response.items.forEach( function (item) {
items.push( App.Item.create(item) );
});
return items;
});
}
});
NOTE: the items is the object I think, but I do not know how it can be generated correctly in php as json data as multi-level array.
Also, one more question, should I use json_encode or not? Because I saw tutorial mentioning that Emberjs uses jsonp... is it a special format? How should I approach this jsonp in PHP?
Thanks!
回答1:
You can simply do
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
$resultArray[] = $row;
}
$resultJSON= json_encode(array("items"=>$resultArray));
Good luck
来源:https://stackoverflow.com/questions/19791068/return-json-data-from-php-for-emberjs-in-the-right-format-with-getjson