Foreach empty from json - php

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.

Related

PHP get JSON key value from specific object

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

Why does json_encode put square brackets around my json object?

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

Decode json in php and create variables

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.
You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

PHP JSON data foreach problem

I want to make a PHP JSON data foreach, but I met some problem. First: I can not get the properties part. Second it alawys show wrong in line: echo '<div class="image">...
Fatal error: Cannot use object of type stdClass as array in ...
This is the json data:
[
{
"post_id": "504464716_189878284371815",
"message": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"attachment": {
"media": [
{
"href": "http:\/\/www.facebook.com\/photo.php?fbid=493710409716&set=a.453260184716.254996.504464716",
"alt": "",
"type": "photo",
"src": "http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs049.snc4\/34793_493710409716_504464716_5821684_2056840_s.jpg",
"photo": {
"aid": "2166659457206182932",
"pid": "2166659457211749620",
"owner": 504464716,
"index": 24,
"width": 225,
"height": 225
}
}
],
"name": "Wall Photos",
"href": "http:\/\/www.facebook.com\/album.php?aid=254996&id=504464716",
"caption": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"description": "",
"properties": [
{
"name": "By",
"text": "Suman Acharya",
"href": "http:\/\/www.facebook.com\/profile.php?id=504464716"
}
],
"icon": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/yD\/r\/aS8ecmYRys0.gif",
"fb_object_type": "album",
"fb_object_id": "2166659457206182932"
},
"action_links": null,
"privacy": {
"value": ""
}
},
...
]
Here is my php code:
foreach ($data as $result) {
echo '<div class="title">'.htmlspecialchars($result->message).'<br />'.htmlspecialchars($result->description).'<br />'.htmlspecialchars($result->caption).'<br />';
if(!empty($result->attachment->properties[0]->text)){
foreach ($result->attachment->properties[0] as $properties) {
echo htmlspecialchars($properties->name).'<br />'.htmlspecialchars($properties->text).'</div>';
}
}
if(!empty($result->attachment->media)){
echo '<div class="image"><img src="'.htmlspecialchars($result->attachment->media[0]->src).'" /><br>'.htmlspecialchars($result->attachment->media[0]->type).'</div>';
}
}
If i were you i would just force the decoding to an assoc array by true as the second arg to json_decode. If you cant or dont want to do that then try accessing it like this:
$result->attachment->media->{0}->href
Use json_decode($the_data, true); instead of json_decode($the_data); that way it will return you an associative array instead of a StdClass.

imploding array_keys from Facebook JSON data

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),",")

Categories