I am currently working to parse through FB api data. Take the following for example...
{
"data": [
{
"id": "ID",
"name": "Creative!"
},
{
"id": "ID",
"name": "a name"
}
],
"paging": {
"cursors": {
"after": "fdsagfsganhdfs==",
"before": "gfdwiolrukjhteqrfgbh"
}
},
"summary": {
"total_count": 2
}
}
This is an example of what is returned when the Graph API is queried for likes. The issue I am having is that I want a clean way to get the total_count out of this data. Often times it will come in without the summary field if there are no 'likes'. This is easily parsed by doing a few if isset() and if array_key_exists but I will be dealing with a lot of data and this use case applies to many different type of data from FB. Any advice on just getting the total_count field? FQL would work but seems to be deprecated. Thanks.
If the total_count field is in fact the sum of the number of elements in the data array then you can simply use the count function in PHP to count the length of the array.
$json_array = json_decode($fb_json_string, true);
$total_count = (isset($json_array['total_count']))? $json_array['total_count']:((isset($json_array['summary']['total_count']))? $json_array['summary']['total_count']:0);
I don't know if I can make it any uglier, it's simply a suggestion though.
Related
My API call returns a pretty big JSON result and my initial thought was to parse out the two pieces of data I need for each event and create my own array. Does it make more sense to pass around the returned JSON or clean it up for my use throughout the application.
Which is more efficient?
Below is an example of one "Event" each result may have 20-50 events in the data. All I need is the ['resultsPage']['results']['event']['location']['lng'] and ['resultsPage']['results']['event']['location']['lat']:
{
"resultsPage": {
"results": {
"event": [
{
"id":11129128,
"type":"Concert",
"uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag at The Fillmore (April 18, 2012)",
"start": {
"time":"20:00:00",
"date":"2012-04-18",
"datetime":"2012-04-18T20:00:00-0800"
},
"performance": [
{
"artist": {
"id":29835,
"uri":"http://www.songkick.com/artists/29835-wild-flag?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag",
"identifier": []
},
"id":21579303,
"displayName":"Wild Flag",
"billingIndex":1,
"billing":"headline"
}
],
"location": {
"city":"San Francisco, CA, US",
"lng":-122.4332937,
"lat":37.7842398
},
"venue": {
"id":6239,
"displayName":"The Fillmore",
"uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"lng":-122.4332937,
"lat":37.7842398,
"metroArea": {
"id":26330,
"uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"SF Bay Area",
"country": { "displayName":"US" },
"state": { "displayName":"CA" }
}
},
"status":"ok",
"popularity":0.012763
}, ....
]
},
"totalEntries":24,
"perPage":50,
"page":1,
"status":"ok"
}
}
My subjective answer is to just use the entire response in your application, grabbing only what you need when you need it. Taking the time to extract only the data you need might be an unnecessary optimization, and your time could be better spent elsewhere.
Optimize only what you measure. If you can measure your application execution time, perhaps with the help of a profiler, like this one with Xdebug, then you can use data to make an informed decision to optimize in this way. My guess is that your application could use optimizations elsewhere before you make this one, but again, without data, it's just a guess.
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
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'];
I have indexed a document in ElasticSearch that contains arrays like this:
{
"student": "John",
"sport": "Soccer",
"match":
{
"eventType": "League",
"date": "2013-12-31T11:00:00.000Z"
}
}
I need to perform a query that searches for, for example, all league matches (ie, where doc["match"]["eventType"] == "League")
I am using the ElasticSearch-PHP api 1.1.0 and tried querying as such as this without success:
$params['body']['query']['match']['match']['eventType'] = 'League';
I also tried:
$params['body']['query']['match']['match']->eventType = 'League';
What is the correct way to do such a search? The documentation has no such examples.
Can you convert this JSON to php object?
{
"query": {
"match": {
"match.eventType": "League"
}
}
}
I think this will do the work.
As a first step, try to use a different name for your soccer 'match' and call it 'game' to prevent causing a collision with the use of the 'match' operation.
I've been recently working with facebook graph api , when I'm pulling user's recents status messages using https://graph.facebook.com/me/statuses?access_token=... all I get is a long list which contains details about the status content, and I want to pull the names of people who liked the status.
The current solution I've been thinking about is using preg match,
I'd like to know if you guys have any other suggestions,
Thanks in advance
I'm not sure what path you're using, but you can fetch the list of users who like a particular status update by requesting the likes connection on an update.
For example, requesting https://graph.facebook.com/10150710880081168/likes yields something like the following for me:
{
"data": [
{
"id": "276700623",
"name": "Vikki Carter"
},
{
"id": "1514365200",
"name": "Darren Bean"
},
{
"id": "539760281",
"name": "Ian Sidaway"
}
],
"paging": {
"next": "https://graph.facebook.com/10150710880081168/likes?format=json&limit=25&offset=25&__after_id=539760281"
}
}
You'll need the ID of the status update, but also the user_status permission from the logged-in user.
EDIT: Iterating over the returned data and assigned users into an array:
<?php
$result = $facebook->api('[status_id]/likes');
$names = array();
foreach ($result['data'] as $user) {
$names[] = $user['name'];
}
You should now have an array of names of users who liked the status in question.