I have a function in PHP which is below:
public function displayMenuType() {
$stmt = $this->conn->query("SELECT * FROM `Type`") or die($this->conn->error);
$json = array();
if($stmt) {
while($result = mysqli_fetch_all($stmt,MYSQLI_ASSOC)) {
$json = json_encode($result, JSON_PRETTY_PRINT);
}
echo $json;
} else {
return false;
}
}
The problem is, the output isn't like I'd expect to see from a json object, it's all on one line and for some reason inside an array/square brackets. Where have I went wrong? The output is below:
[ { "ID": "1", "Type": "Classic Starters", "Description": "" }, { "ID": "2", "Type": "Special Starters", "Description": "" }, { "ID": "3", "Type": "Tapas Menu", "Description": "" }, { "ID": "4", "Type": "Speciality Curry Dishes", "Description": "" }, { "ID": "5", "Type": "Healthier Options", "Description": "Using coconut oil or coconut milk, no ghee, no sugars, we present our healthier range of curries." }, { "ID": "6", "Type": "Traditional Curries", "Description": "" }, { "ID": "7", "Type": "Tandoori & Grilled", "Description": "" }, { "ID": "8", "Type": "Biryanis", "Description": "" }, { "ID": "9", "Type": "Stir Fry's", "Description": "Our new range of Stir fry\u2019s, all made with chicken tikka, served with salad & mint sauce." }, { "ID": "10", "Type": "Nanbabs", "Description": "A choice of Stirfry\u2019s made with chicken tikka, served on a fresh nan bread with mint sauce." }, { "ID": "11", "Type": "Vegetarian Side Dishes", "Description": "" }, { "ID": "12", "Type": "Rice & Chips", "Description": "" }, { "ID": "13", "Type": "Rice Box", "Description": "" }, { "ID": "14", "Type": "Breads", "Description": "" }, { "ID": "15", "Type": "Dips & Drinks", "Description": "" } ]
The square brackets mean a JSON array, which you want, as you want a json array of rows, I'm assuming.
Try this:
if($stmt) {
$array = array();
while($result = mysqli_fetch_all($stmt,MYSQLI_ASSOC)) {
$array[] = $result;
}
$json = json_encode($array, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $json;
exit;
}
According to its documentation mysqli_fetch_all() returns a set of rows (an array). Because this array has numeric integer consecutive keys, it is encoded as a Javascript array by json_encode(). The outer square brackets in the generated JSON denote this array.
Each item of the array returned by mysqli_fetch_all() is an array itself but, because of the MYSQLI_ASSOC argument, they are associative arrays, i.e. they have string keys. Such arrays are encoded as Javascript objects by json_encode(). They are enclosed in curly braces in the JSON. F.e. { "ID": "1", "Type": "Classic Starters", "Description": "" }
The argument JSON_PRETTY_PRINT tells json_encode() to produce a nicely formatted JSON that can be easily read by humans. But everything is in vain if you echo the value it returns in HTML context and then look at it in the browser. The browser doesn't care about the newlines and spaces; it renders any sequence of spaces and newlines as a single white space.
Check the source code of the page in the browser and you'll see the JSON pretty formatted.
Well the obvious error is that you are Over Writing $json each time round the loop.
Then also build an complete array of all the results and then once complete convert it to a JSON String.
public function displayMenuType() {
$stmt = $this->conn->query("SELECT * FROM `Type`")
or die($this->conn->error);
$json = array();
if($stmt) {
while($result = mysqli_fetch_all($stmt,MYSQLI_ASSOC)) {
$json[] = $result;
}
echo json_encode($json);
} else {
return json_encode(['result'=>false]);
}
}
mysqli_fetch_all returns all of the results from your query, which will be represented as an array of associative arrays. The square brackets are array syntax, so the square brackets are properly present if the goal is to show a JSON entity. Without the square brackets, a JSON parser word know how to interpret the commas between each object.
There are a few things you can do to improve your code, like appending to your array instead of potentially overwriting it each loop.
$json = array();
if ($stmt) {
while ($row = mysqli_fetch_assoc($stmt)) {
$json[] = $row;
}
echo json_encode($json);
} else {
return false;
}
Related
Ive got the following JSON:
{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}
I also have another JSON that gives me the ID I want to search for.
For example: "d671ac7d-3b5a-4777-8510-6e8e58295061".
I want to search for the JSON Object, that contains that ID and get the value of the name key. I tried with loops and if, else's but I didn't manage to get it working.
Thanks for your help!
decode the json as array object then loop through with the ID that u want to search
<?php
$json = '{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}';
$j = json_decode($json, true);
foreach($j['servers'] as $arr)
{
if( $arr['id'] == 'd671ac7d-3b5a-4777-8510-6e8e58295061' ) echo $arr['name'];
}
demo: https://3v4l.org/0DboX
I have never used JSON before so apologies if this is a simple request.
I have a webhook setup that sends me a JSON Post (Example Below) - I want to extract the two answers from this "text":"250252" & {"label":"CE"}
{
"event_id": "1",
"event_type": "form_response",
"form_response": {
"form_id": "VpWTMQ",
"token": "1",
"submitted_at": "2018-05-22T14:11:56Z",
"definition": {
"id": "VpWTMQ",
"title": "SS - Skill Change",
"fields": [
{
"id": "kUbaN0JdLDz8",
"title": "Please enter your ID",
"type": "short_text",
"ref": "9ac66945-899b-448d-859f-70562310ee5d",
"allow_multiple_selections": false,
"allow_other_choice": false
},
{
"id": "JQD4ksDpjlln",
"title": "Please select the skill required",
"type": "multiple_choice",
"ref": "a24e6b58-f388-4ea9-9853-75f69e5ca337",
"allow_multiple_selections": false,
"allow_other_choice": false
}
]
},
"answers": [
{
"type": "text",
"text": "250252",
"field": {
"id": "kUbaN0JdLDz8",
"type": "short_text"
}
},
{
"type": "choice",
"choice": {
"label": "CE"
},
"field": {
"id": "JQD4ksDpjlln",
"type": "multiple_choice"
}
}
]
}
}
I have this currently in my PHP file:
$data = json_decode(file_get_contents('php://input'));
$ID = $data->{"text"};
$Skill = $data->{"label"};
This does not work and all I get is null - Any help would really be appreciated, Thank You.
You need to look at the JSON object you're receiving to know the structure of the object you're receiving after using json_decode, what you're trying to get is in $data->form_response->answers, So you can have a variable for easier access:
$answers = $data->form_response->answers;
remember $answers is an array
So to achieve what you're trying to get, you can do:
$data = json_decode(file_get_contents('php://input'));
$answers = $data->form_response->answers;
$ID = $answers[0]->text;
$Skill = $answers[1]->choice->label;
How to access element of below json output using php ..
{
"ISBN:9781430215752": {
"bib_key": "ISBN:9781430215752",
"preview":
"restricted",
"preview_url":
"https://archive.org/details/linuxrecipesforo00kuhn",
"info_url": "https://openlibrary.org/books/OL23936576M/Linux_recipes_for_Oracle_DBAs",
"details": {
"lc_classifications": ["QA76.9.D3 K84 2009"],
"latest_revision": 2,
"ocaid": "linuxrecipesforo00kuhn",
"contributions": ["Kim, Charles.", "Lopuz, Bernard."],
"source_records": ["marc:marc_loc_updates/v37.i44.records.utf8:10470755:1047"],
"title":
"Linux recipes for Oracle DBAs",
"languages": [{
"key": "/languages/eng"
}],
"subjects": ["Linux", "Oracle (Computer file)", "Relational databases", "Database management"],
"publish_country": "cau",
"by_statement": "Darl Kuhn, Charles Kim, Bernard Lopuz.",
"type": {
"key": "/type/edition"
},
"revision": 2,
"other_titles": ["Linux recipes for Oracle DataBase Administrators"],
"publishers": ["Apress", "Distributed to the book trade by Springer-Verlag"],
"last_modified": {
"type": "/type/datetime",
"value": "2014-04-06T06:55:36.956977"
},
"key": "/books/OL23936576M",
"authors": [{
"name": "Darl Kuhn",
"key": "/authors/OL1484587A"
}],
"publish_places": ["Berkeley, CA", "New York"],
"oclc_number": ["243543902"],
"pagination": "xxv, 501 p. :",
"created": {
"type": "/type/datetime",
"value": "2009-11-24T23:42:39.524606"
},
"dewey_decimal_class": ["005.75/65 22", "005.26/8"],
"notes": {
"type": "/type/text",
"value": "Includes index."
},
"number_of_pages": 501,
"isbn_13": ["9781430215752"],
"lccn": ["2009277832"],
"isbn_10": ["1430215755"],
"publish_date": "2008"
}
}
}
I tried using below code,
it doesn't work.
$json = json_decode($body);
echo $json->ISBN:9780980200447->info_url;
It's giving an error..
Is there any other easy way to read all elements?
You are on the right track. : is just an invalid character for a property and must be handled special.
echo $json->{'ISBN:9781430215752'}->info_url;
will get you the expected result.
You may also decode as an associative array
$json = json_decode($body, true);
echo $json['ISBN:9781430215752']['info_url'];
I would probably stick to this approach rather than the object oriented, since encapsulating keys makes code less readable
You must use
echo $json->{'ISBN:9780980200447'}->info_url;
since 'ISBN:9780980200447' is your class name.
Reference: php.net
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
Use braces like this:
echo $json->{'ISBN:9781430215752'}->info_url;
I have the following url:
https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json
which I then do:
$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);
which produces e.g.
{
"data": [
{
"name": "yo yo yo",
"category": "Entertainer",
"id": "45640987076",
"created_time": "2012-04-18T16:14:09+0000"
},
{
"name": "Tony Smith",
"category": "Musician/band",
"id": "456456456456",
"created_time": "2012-02-22T06:56:18+0000"
},
{
"name": "Stations",
"category": "Company",
"id": "567657567",
"created_time": "2012-01-30T23:08:39+0000"
}
]
}
and I then want to list e.g. all the names returned so:
foreach ($likesList->data as $element2){
$name = $element2[name];
echo $name;
}
But it's empty?
See this visualization of your data structure.
As you are receiving an array, you need $list["data"] and not $list->data. Also don't forget to quote the array key "name".
foreach ($likesList['data'] as $element2){
$name = $element2['name'];
echo $name;
}
After json_decode with parameter true you will have associative array. You can access to value by string key. Like in example above.
Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")