Retrieve objects inside json array - php

I'm trying to retrieve team1 score however i cant seem to figure out how to output this. So far i've got this to work where $obj is the json output.
$obj->recent
JSON
"recent": [
[
{
"match_id": "64886",
"has_vods": false,
"game": "dota2",
"team 1": {
"score": "",
"name": "Wheel Whreck While Whistling",
"bet": "7%"
},
"team 2": {
"score": "",
"name": "Evil Geniuses DotA2",
"bet": "68%"
},
"live in": "1m 42s",
"title": "Wheel Whreck... 7% vs 68% Evil...",
"url": "",
"tounament": "",
"simple_title": "Wheel Whreck... vs Evil...",
"streams": []
}
]

You need to use json_decode(); This function returns proper object with arrays and objects inside. Now you need check what is an object and what is an array.
$obj = json_decode($obj, true);
$obj->recent; //array
$obj->recent[0]; //first element of array
$obj->recent[0][0]; //first element of second array
$obj->recent[0][0]->{'team 1'}; //access to object team 1
$obj->recent[0][0]->{'team 1'}->score; //access to property of object team 1
You can find this helpful to understand what happens;
You can also check example on json_decode documentation
If you use var_dump function on $obj it will show you what is an array and what is an object.

You'll want to use json_decode to get that into an array. It looks like recent is an array of arrays of objects. So, you'll do something like
$json = json_decode($obj->recent, true);
$team1 = $json[0][0]['team 1']; //should return array
$score = $team1['score']
edit: Thanks for the comment, was missing a true as the second param in json_decode

Related

How to filter data properties coming from API in PHP?

I have this data coming from an API, the tmdb api, and I want to create an api to filter the data and expose just the properties I need. In this case I just want my endpoint to expose id, title, and overview and nothing else. How can filter these properties with PHP in order to get and expose just the properties I need?
"results:[{
"vote_count": 779,
"id": 420817,
"video": false,
"vote_average": 7.2,
"title": "Aladdin",
"popularity": 476.676,
"poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
"original_language": "en",
"original_title": "Aladdin",
"genre_ids": [
12,
14,
10749,
35,
10751
],
"backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
"adult": false,
"overview": "A kindhearted street..."
}],
The expected result should be:
myapi.com/api
"results:[{
"id": 420817,
"title": "Aladdin",
"overview": "A kindhearted street ..."
}],
$json = json_decode($data);
$results = $json->results;
$results= array_map(function($r){
return ["id" => $r->id, "title" => $r->title, "overview" => $r->overview]
}, $results)
echo json_encode($results);
You can filter the array like this:
function myFilter($result) {
$filtered_array = array();
foreach($result as $movie) {
$filtered_movie = array();
$filtered_movie['id'] = $movie['id'];
$filtered_movie['title'] = $movie['title'];
$filtered_movie['overview'] = $movie['overview'];
array_push($filtered_array, $filtered_movie);
}
return $filtered_array;
}
Just pass the unfiltered array to the function and you'll get the filtered one back.
EDIT:
If your data is in JSON format you will need to use json_decode() to turn it in to an array in PHP. And if you want to return it as JSON then use json_encode() for that.

How to extract data inside JSON response from Zoho CRM API

I'm working with the Zoho CRM. The response format I get from their API seems a bit odd to me; I can't just pull an object from it like I would normally. I'm trying to parse the results using PHP. Here's an example of their response formatting:
{
"response": {
"result": {
"SalesOrders": {
"row": {
"FL": [
{
"content": "6666666000000000000",
"val": "SALESORDERID"
},
{
"content": "Order",
"val": "Subject"
},
{
"content": "Pending",
"val": "Status"
},
{
"content": "John Smith",
"val": "Order Owner"
},
{
"content": "Canada",
"val": "Billing Country"
},
{
"product": {
"FL": [
{
"content": "5555555000000000000",
"val": "Product Id"
},
{
"content": "Roller Coaster",
"val": "Product Name"
}
],
"no": "1"
},
"val": "Product Details"
},
"content": "Pending",
"val": "Ticket Status"
}
],
"no": "1"
}
}
},
"uri": "/crm/private/json/SalesOrders/getRecordById"
}
}
What I'm trying to do is get the Product ID of the Product (in this case the value is "5555555000000000000".
Every response has the same structure, but I can't use the index to parse out the key/value because the amount of fields could change between API calls (meaning the index of product could be 5, like above, or 7, or 8, or whatever depending on the amount of fields being pulled in). I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)? That's the only way I could think of and it doesn't seem very efficient.
PHP has a function for that: json_decode. See http://php.net/manual/en/function.json-decode.php
$response = "... your JSON response from wherever ...";
$data = json_decode($response, true);
// Access the nested arrays any way you need to, such as ...
$orders = $data["response"]["result"]["SalesOrders"];
foreach ($orders["row"]["FL"] as $item) {
if (array_key_exists("product", $item) {
echo $item["product"]["FL"][0]["content"];
}
}
EDIT: Corrected 2nd arg to json_decode (thanks Marcin)
I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Yes, there could be a key=>value pair, but that would be to easy.
Because Zoho ... ;)
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)?
No, (even if you turn this into an array using json_decode($data, true) and go forward by using named keys) you end up iterating or testing for key existence (need to get to product-FL-val to get product-FL-content). Maybe array_fiter or array_walk with a callback come to rescue, but they also iterate internally.
My suggestion is to simply safe some time and use an existing package, e.g.
https://github.com/cristianpontes/zoho-crm-client-php
or search one on Packagist https://packagist.org/search/?q=zoho
I dont know this might help or not. But this is what i am using for my Zoho APP. Actually I am developing a PHP app using Zoho. Your JSON and mine is same but i am getting Deals and you are fetching SalesORders.
<?php
$token = $_SESSION['token'];
$url = "https://crm.zoho.com/crm/private/json/Deals/getRecordById?authtoken=$token&scope=crmapi&id=$dealID";
$result = file_get_contents($url);
$deal_detail = json_decode($result);
$deal_detail = json_decode(json_encode($deal_detail), True);
$deal_detail_array = array();
//Instead of Deals you have SalesOrder right
foreach($deal_detail['response']['result']['Deals']['row']['FL'] as $array){
$deal_detail_array[$array['val']] = $array['content'];
}
echo $deal_detail_array['DEALID']; // You can change this to SALEORDERID, get data correctly every time.
echo $deal_detail_array['Deal Name'];
echo $deal_detail_array['Amount'];
///.......and so on ..............//
//................................//
Only the difference between your JSON and mine is: You have "SalesOrders" in your JSON after result field and in my json instead of SalesOrders i have Deals there.
this code is working fine for me. SO you can do same thing except a field update. I am getting DEALID correctly for each request similarly you can get you SALESORDERID

Targeting object within array JSON Steam API

How do I access webm->max in this Steam API? It's the order [{ that confuses me, array of one before object? I'm not quite sure about the targeting here..
I've tried:
$gameTrailer = $game_json->57690->data->movies[0]->webm->max;
and
$gameTrailer = $game_json['57690']['data']['movies']['webm']['max'];
The API text is like this:
"movies": [{
"id": 2029441,
"name": "Tropico 4 Gameplay Trailer",
"thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie.293x165.jpg?t=1447358847",
"webm": {
"480": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie480.webm?t=1447358847",
"max": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2029441\/movie_max.webm?t=1447358847"
},
"highlight": true
}],
and "movies" lies within:
{"57690": {
"data": {
Assume I'll always want the very first movie in an array (which in this case is an array of one). Thanks in advance.
Correct syntax:
$game_json->{57690}->data->movies[0]->webm->max
When you have an object with a numeric key, you have to wrap the key name by curly brackets (Numeric keys are not valid property names).
If you use the associative option:
json_decode( $data, True );
your second attempt is almost right. Simply add the correct index after movie:
$gameTrailer = $game_json['57690']['data']['movies'][0]['webm']['max'];

Comparing JSON arrays by a specific key in PHP

I want to use the data from array A (below), but only when the item ID from array A does NOT match an ID from items in array B (also, below). How would I go about comparing these two JSON array's by the key of ID (from items) via PHP? I imagine I first need to convert them with json_decode, but I'm not sure where to go after that?
Please note that array B has more nests ("items", "something", & "posts"), unlike array A. I want to compare the ID from items, not posts.
Array A:
{
"data": [{
"category": "Games",
"id": "45345"
},
{
"category": "Music",
"id": "345345345"
},
{
"category": "Food",
"id": "1"
},
{
"category": "Pets",
"id": "13245345"
}]
}
Array B:
{
"data": {
"something": "blah",
"posts": [{
"id": "34241",
"title": "orange"
}],
"items": [{
"id": "1",
"name": "orange"
},
{
"id": "2",
"name": "dog"
},
{
"id": "3",
"name": "cat"
},
{
"id": "4",
"name": "apple"
}]
}
}
With the case above, it would run through array A and output everything from array A except for the third item, since the id of that item (1) matches one of the id's in array B items.
Based on my understanding, you need a two step process. The first is extracting the ids from the first JSON blob, and the second is filtering the second JSON blob. So basically, we have map and filter. And it just so happens we can use PHP's inbuilt functions for this:
$ids = array_map(
function($value) {
return $value['id'];
},
$array2['data']['items']
);
First, we flatten the second array's items element into the individual ids. We "map" over the data.items array, and return the $id attribute of each array. Now, we have an array of ids...
$new = array_filter(
$array1['data'],
function($var) use ($ids) {
return !in_array($var['id'], $ids);
}
);
Now, we use that to filter the first blobs array to determine if an element is new or not. So we use array filter to handle it for us. All we need to do is check the $ids array to see if the current data's id is there (and if it is, throw it away). So we want to filter the array to be only variables that are not in array of $ids (hence !in_array($var['id'], $ids)...)
Decode the items into PHP arrays. Use a SPL like array_diff() to get the results of a diff comparison.
Referances to get you started:
http://www.php.net/manual/en/function.array-diff.php
http://php.net/manual/en/function.array-diff-key.php
http://www.php.net/manual/en/function.json-decode.php
Should be about what your looking for

Store Array thats Located Inside Object

I have the following JSON:
"list": {
"list_id": "2kA",
"title": "Social Media",
"description": "Trending",
"image": [
"http://cdn.socialmediaexaminer.com/wp-content/uploads/2012/11/br-campaign-report.png?9d7bd4",
"http://cdn.socialmediaexaminer.com/wp-content/uploads/2012/11/br-campaign-report.png?9d7bd"
],
"views": 65
}
How can I store a serialized version of the image array in the database? Doing any of the following returns an error:
$images = $item->list->image;
$images = $item->list->image->[0];
$images = $item->list->['image'];
Thanks guys!
In your DB, data is in JSON, literally it means its a formatted string like:
"something here...."
You cannot access it by "->" as it is not an object.
So,
Convert your string(JSON) to Object to access like these:
$x['list']['image']
It can be achieved by json decoding your string which will convert your string to object
There was a bad error in code too. This one : $item->list->image->[0];
you cannot access an element of an array like this image->[0] --> it should be
$item->list->image[0]
you can access to your images like this:
foreach($item->list->image as $your_image) {
//do what you want
}
or use a associated array like this
$x = json_decode('{"list": {
"list_id": "2kA",
"title": "Social Media",
"description": "Trending",
"image": [
"a",
"b"
],
"views": 65
}}', true);
foreach($x['list']['image'] as $your_image) {
//do what you want
}
to save it to your db use json_encode (and escape), as example of a mysqli connection
$query = 'INSERT INTO your_table (...)
VALUES (\''.mysqli_real_escape_string($dblink, json_encode($your_array)).'\')';
on select you can use json_decode!

Categories