Getting JSON data from API as array or object - php

I am using sports-radar API to get the schedule of NFL week 1. The API returns the following data in json format (I shortened string for example).
"id": "8e45fe2d-fb95-4504-845d-7c815623ccd6",
"year": 2018,
"type": "REG",
"name": "REG",
"week": {
"id": "37435167-5cf6-4cce-b405-ff0e264ced9c",
"sequence": 1,
"title": "1",
"games": [{
"id": "0822b924-eadc-4398-bfe6-83cbbf3a2912",
"status": "scheduled",
"reference": "57570",
"number": 4,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "6ed18563-53e0-46c2-a91d-12d73a16456d",
"name": "Lucas Oil Stadium",
"city": "Indianapolis",
"state": "IN",
"country": "USA",
"zip": "46225",
"address": "500 South Capitol Avenue",
"capacity": 67000,
"surface": "artificial",
"roof_type": "retractable_dome"
},
"home": {
"id": "82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9",
"name": "Indianapolis Colts",
"alias": "IND",
"game_number": 1
},
"away": {
"id": "ad4ae08f-d808-42d5-a1e6-e9bc4e34d123",
"name": "Cincinnati Bengals",
"alias": "CIN",
"game_number": 1
},
"broadcast": {
"network": "CBS"
}
}, {
"id": "0a456149-c547-4856-9b1b-86e1d93887ae",
"status": "scheduled",
"reference": "57574",
"number": 8,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "3c85d89a-ec66-4983-acd5-1381d6c8673a",
"name": "Mercedes-Benz Superdome",
"city": "New Orleans",
"state": "LA",
"country": "USA",
"zip": "70112",
"address": "1500 Sugar Bowl Drive",
"capacity": 73208,
"surface": "artificial",
"roof_type": "dome"
},
"home": {
"id": "0d855753-ea21-4953-89f9-0e20aff9eb73",
"name": "New Orleans Saints",
"alias": "NO",
"game_number": 1
},
"away": {
"id": "4254d319-1bc7-4f81-b4ab-b5e6f3402b69",
"name": "Tampa Bay Buccaneers",
"alias": "TB",
"game_number": 1
},
"broadcast": {
"network": "FOX"
I used the following website as a tutorial on how to display only the the data I need and how to loop over it
Note the JSON string is stored in the variable $schedule
MY Code
// JSON string
$jsonData = $schedule; //get json string
// Convert JSON string to Array
$jsonArray = json_decode($jsonData, true);
// Convert JSON string to Object
$jsonObject = json_decode($schedule);
Looping through PHP Array or Object
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"] . ", " . $value["away"] . "<br>";
}
// Loop through Object
$someObject = jsonObject
foreach($someObject as $key => $value) {
echo $value->home . ", " . $value->away . "<br>";
}
My ERRORS
When trying to convert the string to an array and attempting to get the away team name I get the error Illegal string offset 'away' same problem with home and all other data
When trying to access data as an object I get the following error Trying to get property of non-object
I followed the tutorial to the letter. Yet im getting the basic errors above...? Any help and explanation would be appreciated. Thank you
EDIT:
var_export($schedule) returns the following:
array ( 'id' => '8e45fe2d-fb95-4504-845d-7c815623ccd6', 'year' => 2018, 'type' => 'REG', 'name' => 'REG', 'week' => array ( 'id' => '37435167-5cf6-4cce-b405-ff0e264ced9c', 'sequence' => 1, 'title' => '1', 'games' => array ( 0 => array ( 'id' => '0822b924-eadc-4398-bfe6-83cbbf3a2912', 'status' => 'scheduled', 'reference' => '57570', 'number' => 4, 'scheduled' => '2018-09-09T17:00:00+00:00', 'entry_mode' => 'INGEST', 'venue' => array ( 'id' => '6ed18563-53e0-46c2-a91d-12d73a16456d', 'name' => 'Lucas Oil Stadium', 'city' => 'Indianapolis', 'state' => 'IN', 'country' => 'USA', 'zip' => '46225', 'address' => '500 South Capitol Avenue', 'capacity' => 67000, 'surface' => 'artificial', 'roof_type' => 'retractable_dome', ), 'home' => array ( 'id' => '82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9', 'name' => 'Indianapolis Colts', 'alias' => 'IND', 'game_number' => 1, ),

You are dealing with array of arrays. Try something like this:
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"]["name"] . ", " . $value["away"]["name"] . "<br>";
}

Related

PHP Array and Updating an Array with data from another nested array [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I replace a specific key's value in an array in php?
(2 answers)
Closed 7 months ago.
I all, I've been staring at this for hours so any help is greatly appreciated. I have an array...
$aircraft = [
'N7826C' => ['nnum' => 'N7826C', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N226PD' => ['nnum' => 'N226PD', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N326PD' => ['nnum' => 'N326PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N826PD' => ['nnum' => 'N826PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0']
];
With that array, I implode it to get a list of the nnums to pass through a API....
$aircraftNNUMlist = implode(',', array_map(function($v) { return $v['nnum']; }, $aircraft));
$json = file_get_contents('https://airlabs.co/api/v9/flights?_fields=reg_number,lat,lng&reg_number='.$aircraftNNUMlist.'&api_key=XXXXX');
That API returns...
{
"request": {
"lang": "en",
"currency": "USD",
"time": 15,
"id": "c9by9lmq1q0",
"server": "z",
"host": "airlabs.co",
"pid": 322387,
"key": {
"id": 19146,
"api_key": "xxxxxxxxxxxxxxxx",
"type": "free",
"expired": "2022-08-20T22:00:00.000Z",
"registered": "2022-07-19T03:51:04.000Z",
"limits_by_hour": 2500,
"limits_by_minute": 250,
"limits_by_month": 1000,
"limits_total": 628
},
"params": {
"_fields": "reg_number,lat,lng",
"reg_number": "N60NT,N40NT,N30NT,N10NT",
"lang": "en"
},
"version": 9,
"method": "flights",
"client": {
"ip": "xxxxxxxxxxxxxxxxx",
"geo": {
"country_code": "US",
"country": "United States",
"continent": "North America",
"city": "Provo",
"lat": 40.2181,
"lng": -111.6133,
"timezone": "America/Denver"
},
"connection": {
"type": "corporate",
"isp_code": 46606,
"isp_name": "Unified Layer"
},
"device": {},
"agent": {},
"karma": {
"is_blocked": false,
"is_crawler": false,
"is_bot": false,
"is_friend": false,
"is_regular": true
}
}
},
"response": [
{
"reg_number": "N60NT",
"lat": 34.11,
"lng": -117.69
}
],
"terms": "Unauthorized access is prohibited and punishable by law. \nReselling data 'As Is' without AirLabs.Co permission is strictly prohibited. \nFull terms on https://airlabs.co/. \nContact us info#airlabs.co"
}
I am having trouble looping through the "response" of the API return (stored at $json) to update the corresponding index in $aircraft. If a nnum isn't currently active there will not be a entry in "response" for instance "response" only has N60NT in the return array. I am fairly new to arrays so I've been taking swings in the dark and nothing seems to be right.
I presume you have json_decoded your api json response into a PHP array. Well actually:
$arr = json_decode($json_form_api, true);
$response = $arr["response"];
foreach ($response as $sub) {
$reg = $sub["reg_number"];
$aircraft[$reg]["lat"] = $sub["lat"];
$aircraft[$reg]["lng"] = $sub["lng"];
}

Need a help to assign array to array element of php

I have created an array to convert into json file in php. But as per the requirement I need to assign an array to this array element. it's an array inside an array.
"data" => array( // data array
array(
"event_name" => "Purchase",
"event_time" => time(),
"event_id" => $order_id,
"user_data" => array(
"client_ip_address" => $ip,
"client_user_agent" => $browser,
"em" => $email,
"ph" => $phone,
"fbc" =>$fbp,
"fbp" =>$fbc,
"fn" => $fn,
"ct" => $ct,
"st" => $st,
"zp" => $zp,
"country" => $country,
"external_id" => $email
),
"contents" => $items,
// "id" => $item_ids,
// "quantity" => count($item_qty),
// // "delivery_category"=> "home_delivery",
// "order_id" => $order_id
// ),
"custom_data" => array(
"currency" => "GBP",
"value" => $order_total,
),
"action_source" => "website",
"event_source_url" => $fullURL,
),
)
);
But my $item array look like this when I echo
{
"id": 814,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Certificate in Strategic Management and Leadership (RQF)",
"product_id": 19555,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "1158",
"subtotal_tax": "0",
"total": "1158",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
},
{
"id": 815,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Diploma in Strategic Management and Leadership (RQF)",
"product_id": 19107,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "999",
"subtotal_tax": "0",
"total": "999",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
}
And when I assign this $items and converted to json then I can see only the ides of the array
"user_data": {
"client_ip_address": "2402:d000:a200:a4a8:f06d:40a:cf85:e26d",
"client_user_agent": "",
"em": "b99526fedef7fe1da29e27d6f09cb64efew536978778e6cde3d8277d71a04398d1a4",
"ph": "db80005a39b11372054b7708cac76gsaaww47af6ed3fe4b37b9a8b2be435e2fcff04a7",
"fbc": "",
"fbp": "",
"fn": "83cd072a16ddb3d793c2f5bcd7d0basdree5a04af680279cf6a26fb8dffe57ce3b51a",
"ct": "17a0730b80e55f4bee9569be3f7e6d0wqw500c5568ecb8d785759d7151ef40f5bbd",
"st": "e3b0c44298fc1c149afbf4c8996fb9sas2427ae41e4649b934ca495991b7852b855",
"zp": "ac7bb74de6884ffce919c15fef4193749sdsd4588026c643973946713ac46da540d",
"country": "c820736841e811c96d30b14eb998feb6bsddc2c9d0764b7731267438dc7d6bb5b59",
"external_id": "b99526fedef7fe1da29e27d6f09ssscb64536978778e6cde3d8277d71a04398d1a4"
},
"contents": [
{
"814": {},
"815": {}
}
],
result should be look like this in this way in "centents" element
"contents" : [{'id':'ABC123','quantity' :2,'item_price':5.99}, {'id':'XYZ789','quantity':2, 'item_price':9.99, 'delivery_category': 'in_store'}]
I think the problem is that your $items, is actually an array of "strings" (json)
try to do a json_decode() on those $items before adding it to the content.
anyway, when you ask a question try to remove all unnecessary stuff, and make an example with the minimum code you need help with, in this case it takes a lot of reading through stuff just to understand the issue.

How to get the only first images in array inside array

Here i have one array(first array) inside i have one more array(second array), now i want to display only first image from second array(galleryImages) , how can do this. i tried but i am not able to get the results
print_r($response);
Array
(
[0] => stdClass Object
(
[gallery_id] => 2
[title] => Annual Day 2017
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg","4.jpg"]
[reg_on] => 2017-05-17 01:55:12
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
[1] => stdClass Object
(
[gallery_id] => 3
[title] => Sports Day
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg"]
[reg_on] => 2017-05-17 01:55:36
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
)
Expected Results
{
"status": "Success",
"data": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
},
{
"gallery_id": "3",
"title": "Sports Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
}
],
}
I tried like this but is i am not getting the exact results
$images = array();
foreach ($response as $key => $value)
{
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count(json_decode($value->galleryImages,true));
$img['gallery'] = json_decode($value->galleryImages,true);
array_push($images,$img);
}
$return=array('status'=>"Success",'Images'=>$images);
echo json_encode($return);
Getting Results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"d17ac9d0aeb6435eaa294e0d69d4cc8f.jpg",
"a91945e0cf55379f51cf5faef10d7a4a.jpg",
"2d1501045ddbb3ccc238e70f9af05027.jpg",
"071c3b5f969bed1d1e2ee4b6531e4444.jpg"
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"f0ba574fd46a01ff5a41855a97c710ca.jpg",
"1d10802f1b74e660117f36bd6dd0aa26.jpg",
"e705fb66f767a1b914200ca8d3cae700.jpg",
"3d5d8828331e13d3decc94021a64e5ca.jpg"
]
}
]
}
Here what happening means gallery is coming an array , for me don't want array i need first image only, please check my expected results, update the answer
Updated expected results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
}
]
}
Instead of [galleryImages] => ["1.jpg","2.jpg","3.jpg"], use for loop to iterate through galleryImages.
Create an associative array with key =>value pair like [galleryImages] => ["galleryimage1" => "1.jpg", "galleryimage2" => "2.jpg", "galleryimage3" => "3.jpg"].
While json_decode you will get intended output.
My changes and explanations are in the code block:
Code: (Demo)
// assumed that previous line was something like $response=json_decode($json);
$response=[
(object)[
'gallery_id'=>2,
'title'=>'Annual Day 2017',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg","4.jpg"],
'reg_on'=>'2017-05-17 01:55:12',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
],
(object)[
'gallery_id'=>3,
'title'=>'Sports Day',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg"],
'reg_on'=>'2017-05-17 01:55:36',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
]
];
foreach ($response as $value){ // removed $key=> because it was unnecessary
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count($value->galleryImages); // removed json_decode()
$img['gallery'] = $value->galleryImages[0]; // removed json_decode and added [0] to access first
$images[]=$img; // swapped push() call with identical function-less "push"
}
if(isset($images)){ // added this condition to ensure there was something to return
$return=array('status'=>"Success",'Images'=>$images);
//var_export($return);
echo json_encode($return);
}else{
// enter some sort of error message / default behavior
}
Output:
{"status":"Success","Images":[{"gallery_id":2,"title":"Annual Day 2017","description":"","galleryImagesCount":4,"gallery":"1.jpg"},{"gallery_id":3,"title":"Sports Day","description":"","galleryImagesCount":3,"gallery":"1.jpg"}]}

How to reproduce with PHP a particular JSON document

I have been trying to solve my problem for days, but without getting the desidred result. Here's a particular structure for a JSON file:
{
"detections": {
"timestamp": "12/04/2016/ 20:25:00",
"rooms": [
{
"name": "r1",
"sensors": [
{
"id": 10,
"type": "rad",
"value": 100,
"valMax": 600,
"valMin": 100
},
{
"id": 12,
"type": "temp",
"value": 30.5,
"valMax": 1000,
"valMin": 0
}
]
},
{
"name": "r2",
"sensors": [
{
"id": 20,
"type": "temp",
"value": 20.7,
"valMax": 1000,
"valMin": 0
},
{
"id": 15,
"type": "rad",
"value": 800,
"valMax": 600,
"valMin": 100
}
]
}
]
}
}
I must encode with that structure data that I've retrieved from MySQL Database.
It consists of three tables linked with foreign key constraints. Now, the code I've written for this is the following:
while($row = mysqli_fetch_array($result)) {
array_push($detections, array("timestamp"=>$row['timestamp'],
"rooms"=>array("name"=>$row['name'],
"sensors"=>array("id"=>$row['id'], "type"=>$row['type'], "value"=>$row['value'], "valMin"=>$row['valMin'],
"valMax"=>$row['valMax']))
));
}
But it gives me this result:
{
"detections": [{
"timestamp": "2016-09-10 17:59:06",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "1",
"type": "prova2",
"value": "12",
"valMin": "1",
"valMax": "12"
}
}
}, {
"timestamp": "2016-09-11 00:41:21",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "1",
"type": "prova2",
"value": "21",
"valMin": "1",
"valMax": "12"
}
}
}, {
"timestamp": "2016-09-10 19:59:20",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "3",
"type": "prova",
"value": "13",
"valMin": "11",
"valMax": "13"
}
}
}, {
"timestamp": "2016-09-11 00:41:21",
"rooms": {
"name": "Stanza dei Giochi",
"sensors": {
"id": "3",
"type": "prova",
"value": "23.5",
"valMin": "11",
"valMax": "13"
}
}
}]
}
which is similar but not the same :/
As I've noticed from the JSON structure I would get, detections with the same timestamp but with different rooms, sensors and values are collected together... but I don't know how to realize that.
Hope y'all can give me a hand, thanks >.<
You are building your array wrong to achieve that structure.
To achieve the desired structure your array needs to look like this
<?php
array (
'detections' =>
array (
'timestamp' => '12/04/2016/ 20:25:00',
'rooms' =>
array (
0 =>
array (
'name' => 'r1',
'sensors' =>
array (
0 =>
array (
'id' => 10,
'type' => 'rad',
'value' => 100,
'valMax' => 600,
'valMin' => 100,
),
1 =>
array (
'id' => 12,
'type' => 'temp',
'value' => 30.5,
'valMax' => 1000,
'valMin' => 0,
),
),
),
1 =>
array (
'name' => 'r2',
'sensors' =>
array (
0 =>
array (
'id' => 20,
'type' => 'temp',
'value' => 20.699999999999999,
'valMax' => 1000,
'valMin' => 0,
),
1 =>
array (
'id' => 15,
'type' => 'rad',
'value' => 800,
'valMax' => 600,
'valMin' => 100,
),
),
),
),
),
);
Check also check json_decode and json_encode

Creating a PHP object with out the use of a key?

I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));

Categories