JSON getting data from multidimensional arrays - php

I have been populating a chart embed with data from a multidimensional PHP array ($result). When printing the array to JSON (using print json_encode($result, JSON_NUMERIC_CHECK);) i got the following array structure:
[
{
"name":"Array1",
"data":[
1,
2,
3
]
},
{
"name":"Array2",
"data":[
1,
2,
3
]
}
]
I used this array to populate my highcharts in the code below. This used to work just fine but after I changed the setup of my array it will now have to be reworked.
$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[1]['data'];
});
The new setup of my $result array after making some changes is the below:
{
"Array1":{
"data":[
"1",
"2",
"3"
]
},
"Array2":{
"data":[
"1",
"2",
"3"
]
}
}
As such, the code I used to populate my Highcharts no longer works. I would very much appreciate if anyone can help me understand how I can rework the $.getJSON code such that it would work with the new array structure. Or maybe inform me if I have to stick with the old array setup? Thanks.

From what I can tell (haven't tested), you just need to change:
$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[1]['data'];
});
To
$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.xAxis.categories = json['Array1']['data'];
chartOptions.chart1.series[0].data = json['Array2']['data'];
});
The change in the JSON structure changed from an array of dictionaries, to a dictionary of dictionaries, so you no longer access it via index, instead you access it by key (Array1, Array2).

Related

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

How to get all children in firebase php?

What I'm trying to do is to get the all the child or users from firebase. Here is the JSON Data:
{
"users":{
"USER1":{
"data1": "123",
"data2": "123"
},
"USER2":{
"data1" : "456",
"data2" : "456"
}
}
}
Does anyone know how to get the child using firebasephp? I am using https://github.com/ktamas77/firebase-php this firebase php.
I'm not a PHP developer so this may not be 100% valid php but looking at the code you would do something possibly like this
$firebase = new Firebase('http://myfirebasename.firebaseio.com', TOKEN);
$users = $firebase->get('/users');
This should return you an array of the data at that endpoint.

Using Idiorm in PHP, how to serialise an ORM object after "find_one()" call

I am using "slim-json-api" in a project to access some data in a MySQL database. I am trying to pull back a single row and return this to the response, but I am getting no data back.
$app->get('/topics/:id', function($id) use ($app) {
$topic = ORM::for_table('topics')->find_one($id);
$posts = ORM::for_table('posts')->where('topics_id', $id)->find_array();
$app->render(200, array(
"topic" => $topic,
"posts" => $posts
));
});
The result of this is as follows:
{
"topic": {},
"posts": [
{
"id": "1",
"user_id": "1",
"topics_id": "1",
"post_time": "2014-03-17 12:44:24",
"post_subject": "I like this!",
"post_text": "This is the body of an amazing post!"
}
],
"error": false,
"status": 200
}
The annoying this about this is that I get a fully populated "posts" object and I know the data is present and correct in the DB. It is as if the array of results for "posts" is not an array of single returned value types.
Any help would be much appreciated.

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

How to turn JSON to object literal using PHP and jquery

Is there a concise neat way to turn an XML feed into an JavaScript object literal?
I have this XML feed
<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>
and wish to turn it to:
var jobs = [
{
"name" : "Technology",
"areas" : [ "Refrigiration" , "Information Technology", "Electronics", "Avionics" ]
},
{
"name" : "Agriculture",
"areas" : [ "Agri-Tourism" , "Animal Husbandry", "Harvesting", "Poultry" ]
},
{
"name" : "Media",
"areas" : [ "Journalism" , "Camera person", "Reality tv person", "Commentator" ]
}
];
I succeeded in encoding the JSON object using php. What I am missing is the rest.
echo json_encode(simplexml_load_string("<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>"));
This gives you:
{
"industry": [
{
"name": "Technology",
"area": [
"Refrigiration",
"Information Technology",
"Electronics",
"Avionics"
]
},
{
"name": "Agriculture",
"area": [
"Agri-Tourism",
"Animal Husbandry",
"Harvesting",
"Poultry"
]
}
]
}
You need to convert your XML to an array, https://stackoverflow.com/questions/4844476/xml-to-php-array
Then you'll need to convert the array to json using php json_encode()
If you are receiving a JSON encoded string in your javascript callback, you probably need to run $.parseJSON() to make jQuery treat it as a JSON object instead of a string
Two solutions:
PURE JQUERY
Using jQuery's parseXML , combined with jQuery get you can have the object you need:
$.get("http://www.example.com/path/to/file.xml", function(data){
var xml = $.parseXML(data);
console.log(xml);
});
PHP+JQUERY
if you've already parsed the object into a json, just print it into an html file and get that file using jquery's getJSON
$.getJSON("http://www.example.com/json/feed",function(data){
console.log(data);
});

Categories