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
Related
So what I have here is a JSON response from my PHP cURL, so I'm trying to get the specific group of array under location depending where is the identifier value I'm checking.
{
"status": "SUCCESS",
"response": {
"offset": 0,
"max": 50,
"count": 2,
"locations":[
{
"identifier":"54320",
"id": 503892,
"name":"The Foo"
},
{
"identifier":"54321",
"id": 503893,
"name":"The Bar"
}
]
}
This is what I've done so far and what I'm trying to do. So I already parse the json above and put it on foreach. Note the identifier is not always an int it can also be string.
$parsed_json = json_decode($phpCurlResponse, true);
$parsed_json = $parsed_json["response"]["locations"];
foreach($parsed_json as $key => $pj){
if($pj['identifier'] == "54320"){
echo $pj['name'].' & '.$pj['id'];//this should display The Foo & 503892
}
}
I have tried this one and it can only see the first group of array under locations but when I change the identifier value from 54321 to 112233 the response will be Identifier do not exist. can you help me how we achieve this.
Your JSON is invalid.
There shouldn't be a comma after the last object in the locations array.
There should be a } after the locations closing array bracket (]).
So is the valid JSON.
{
"status": "SUCCESS",
"response": {
"offset": 0,
"max": 50,
"count": 2,
"locations": [
{
"identifier":"54320",
"id": 503892,
"name":"The Foo"
},
{
"identifier":"54321",
"id": 503893,
"name":"The Bar"
}
]
}
}
Sorry for the premature posting but I want you to know that there's nothing wrong with the code above its just had some typo error on the json response I typed, anyways thank you for the help guys. :) So that's one possible way to get an specific set of array inside an object depending where's the key value you looking for.
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've got an AngularJS frontend and got some problems relating the data layer.
In the frontend I've got contacts.
contact JSON object:
{
"id": 1,
"groupId": 1,
"firstName": "John",
"lastName": "Doe",
"email": "jd#gmail.com",
"company": "Google",
"info": "lorem ipsum dolor amet",
"numbers": [
{
"typeId": 1,
"number": "123456"
},
{
"typeId": 2,
"number": "1234567"
},
{
"typeId": 3,
"number": "8765432"
},
{
"typeId": 4,
"number": "0864235"
}
]
}
I get this object over an url with one http request.
When I will save it I give exactly this object back to the backend.
But how can I e.g. update a number out of the numbers table or the company out of the companies table with php?
My colleague said to me that when i update a number in the contact object, i have to call an url with /numbers/id .
But I just want to put back a "contact object" at /contacts
and let the business layer/data layer do the logic and split the object to update different tables.
In the backend he uses php and fat-free-framework.
Can anyone explain how to do this?
-EDIT-
And I thought the complete logic how to save the data is in the backend.
With DTO (Data Transfer Object) and DAO (Data Access Object) etc.
If you want to accept an object graph then you would need to parse it then make the appropriate calls to the database.
For example, presuming you have a table "numbers" that has columns "typeId" and "number" you would probably want logic in your "contact" class that does something like...
// convert the JSON to PHP
$request = json_decode($contact);
if(isset($request->numbers)) {
$number = new \DB\SQL\Mapper($this->db, "number");
// loop over your number objects
foreach($request->numbers as $data) {
// create a new number entry for each one
$number->copyfrom($data);
$number->save();
$number->reset();
}
}
Obviously how and where you do this would depend on how you have structured your code, for example contact->post() and contact->put() might be applicable places.
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.
I have the following json data:
{
"data": [
{
"name": "The Frugalicious Chef",
"category": "Chef",
"id": "186397894735983",
"created_time": "2011-03-07T16:10:35+0000"
},
{
"name": "Siuslaw Broadband",
"category": "Telecommunication",
"id": "190373850988171",
"created_time": "2011-03-06T20:21:42+0000"
},
{
"name": "Paul",
"category": "Movie",
"id": "129989595478",
"created_time": "2011-03-04T19:55:18+0000"
},
{
"name": "Mark Zuckerberg",
"category": "Public figure",
"id": "68310606562",
"created_time": "2011-02-16T09:50:35+0000"
},
The idea here is that I want to take this data and use parts of it. I want to create a list of the "category's" that are in the data. The problem is that there is and will be multiple items with the same category. So my list will have duplicates that I do not want. The following is how I am getting the data and converting it for use:
$jsonurl = "https://xxxxxxxxxx.com/".$fd_ID. "/info?access_token=".$session['access_token'];
$likesjson = file_get_contents($jsonurl,0,null,null);
$likesArray=json_decode($likesjson);
I then use a foreach to access the data.
foreach($friendLikesArray->data as $l)
{
etc......
}
So I guess muy question is I want to take the $likesArray and pull out all the unique Data->Category->names. Also will want to do sorting, and other things but I will get to that when the time comes.
Thanks for the help in advance.
Neil
The data structure you would want to use is a set, that only allows unique entries.
A simple implementation using PHP arrays is to use the keys.
e.g.
$categories = array();
foreach($friendLikesArray->data as $l)
{
$categories[$l->category] = true;
}
$categories = array_keys($categories);
This way if the category has already been added, then you are not adding anything new to the array.
If the keys are not important to you then you can use the line:
$categories[$l->category] = $l->category
But this means your array won't have 0,1,2...n for keys.