how to validate a json empty object in php - php

my php code works fine when it returns the result like this ->
{
"id": 267935,
"results": [
{
"key": "rc94yWXcyr0",
"name": "Trailer 1",
"site": "YouTube"
},
{
"key": "GZ0Bey4YUGI",
"name": "Official Trailer",
"site": "YouTube"
},
{
"key": "y1fZg0hhBX8",
"name": "Official Trailer 2",
"site": "YouTube"
}
]
}
but i get error
(Notice: Undefined variable: finaltrailers in ... )
when results return like this -->
{
"id": 392344,
"results": [
]
}
and this is my php code -->
$trailer = $json2['results'];
foreach($trailer as $trailers=>$keytrailers){
foreach($keytrailers as $alltrailers=>$allkeytrailers){
if($alltrailers == 'key'){
# $finaltrailers .= $allkeytrailers.',';
}
}
}
echo trim($finaltrailers,",");
how can i validate the empty array and give and error my self ? please help me thank you.

You have to define the variable to use it in trim.
Just add it at the beginning of your code.
$finaltrailers = '';
$trailer = $json2['results'];
foreach($trailer as $trailers=>$keytrailers){
foreach($keytrailers as $alltrailers=>$allkeytrailers){
if($alltrailers == 'key'){
# $finaltrailers .= $allkeytrailers.',';
}
}
}
echo trim($finaltrailers,",");

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

Loop through nested JSON array using PHP [duplicate]

This question already has answers here:
PHP multidimensional array get value by key
(2 answers)
Closed 4 months ago.
I have a JSON array as follows:
[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]
I want to loop through this nested JSON array to retrieve all the "desc" from the "custClass" list using PHP.
Any help would be appreciated.
You can try this way
$json='{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}';
$decode=json_decode($json,true);
$desc=[];
foreach($decode['custClass'] as $cust){
$desc[]=$cust['desc'];
}
var_dump($desc);
You can decode data and loop it
$s = '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
$data =json_decode($s,true);
foreach($data as $obj){
foreach($obj['custClass'] as $val){
echo "Desc ".$val['desc']."<br/>";
}
}
Try decoding data and retrieve it using foreach:
$your_data = your_data;
$decoded_data = json_decode($your_data [0], true);
$final_data = [];
foreach($decoded_data['custClass'] as $data) {
$final_data[] = $data['desc'];
}
print_r($final_data);
try this code
loop this array like below
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
json_decode() the data
<?php
$data= '[
{
"custClass": [
{
"code": "50824109d3b1947c9d9390ac5caae0ef",
"desc": "e1f96b98047adbc39f8baf8f4aa36f41"
},
{
"code": "dab6cc0ed3688f96333d91fd979c5f74",
"desc": "d0e850f728b2febee79e1e7d1186c126"
},
{
"code": "bc4050f8f891296528ad6a292b615e86",
"desc": "bee3120e77092d889c3b9e27cbee75bd"
},
{
"code": "f13fc8c35dfe206a641207c6054dd9a0",
"desc": "32a81cb610805d9255d5f11354177414"
},
{
"code": "2117c346d9b3dfebf18acc8b022326d4",
"desc": "88a8e85db11976082fed831c4c83838e"
},
{
"code": "95c0674fc0e0434f52a60afce74571d2",
"desc": "39c4d4bca1578194801f44339998e382"
},
{
"code": "c8ad6f709612d2a91bb9f14c16798338",
"desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
}
],
"sourceData": [
{
"sourceId": "ff64060a40fc629abf24eb03a863fd55",
"sourceName": "92aa69979215a2bf6290c9a312c5891f"
}
]
}
]';
foreach(json_decode($data) as $key=>$value){
foreach($value->custClass as $key1=>$value1){
echo $value1->desc;
}
}
?>
You can loop through all JSON Arrays by using a recursive algorithm.
$myJsonArray = '<as-your-above-json-array>';
# Convert $myJsonArray into an associative array
$myJsonArray = json_decode($myJsonArray, true);
recursiveArray($myJsonArray);
# A recursive function to traverse the $myJsonArray array
function recursiveArray(array $myJsonArray)
{
foreach ($myJsonArray as $key => $hitElement) {
# If there is a element left
if (is_array($hitElement)) {
# call recursive structure to parse the jsonArray
recursiveArray($hitElement);
} else {
if ($key === 'desc') {
echo $hitElement . PHP_EOL;
}
}
}
}
/**
OUTPUT
e1f96b98047adbc39f8baf8f4aa36f41
d0e850f728b2febee79e1e7d1186c126
bee3120e77092d889c3b9e27cbee75bd
32a81cb610805d9255d5f11354177414
88a8e85db11976082fed831c4c83838e
39c4d4bca1578194801f44339998e382
6b4c4d5f4ae609742c1b6e62e16f8650
*/
Live code -> https://wtools.io/php-sandbox/bFEJ
OR use the RecursiveArrayIterator to traverse the $myJsonArray array
$myJsonArray = json_decode($myJsonArray, true);
$myIterator = new RecursiveArrayIterator($myJsonArray);
recursiveArray($myIterator);
function recursiveArray(RecursiveArrayIterator $myIterator)
{
while ($myIterator->valid()) {
if ($myIterator->hasChildren()) {
recursiveArray($myIterator->getChildren());
} else {
if ($myIterator->key() === 'desc') {
echo $myIterator->current() . PHP_EOL;
}
}
$myIterator->next();
}
}
Live code -> https://wtools.io/php-sandbox/bFEL

JSON Post PHP (TypeForm)

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;

Foreach empty from json

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.

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.

Categories