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.
Related
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).
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
I am using MongoDB with the PHP Library. I inserted a valid JSON document inside MongoDB using PHP. I am now retrieving the document using findOne and am getting a MongoDB\Model\BSONDocument object as a result. How do I get back my JSON document easily? Is there any inbuilt function or will I have to write logic to convert the BSONDocument to JSON?
I didn't see any answers here and I was having the same issue. I did some research and it appears that when you create a document of MongoDB\Model\BSONDocument there is a bsonSerialize() method. This method will return a stdClass Object which is really the PHP Array Class. According to documentation one can then convert from PHP to BSON and then to JSON.
This is crazy looking, but it works. Here is my example $accountResultDoc is of MongoDB\Model\BSONDocument type.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($accountResultDoc))
Results
{
"_id": {
"$oid": "56e1d8c31d41c849fb292184"
},
"accountName": "Michael's Test Company",
"accountType": "Partner",
"subsidiary_id": {
"$oid": "563c3ffbaca6f518d80303ce"
},
"salesforceId": "WERWERWEr2",
"netsuiteExternalId": "56e1d8c31d41c849fb292184",
"suspendBilling": false,
"testAccount": false,
"serviceOrder_ids": null,
"invoice_ids": null
}
The BSONDocument object has a jsonSerialize method. Use that:
Example
{"_id" : 12345,
"filename" : "myfile",
"header" : {
"version" : 2,
"registry" : "test",
"serial" : 20080215,
"records" : 17806,
"startDate" : 19850701,
"endDate" : 20080214
},
}
$connect = new MongoDB\Client('mongodb://yourconnection');
$db = $connect->YourDB;
$collection = $db->YourCollection;
$test = $collection->findOne(array("_id"=>12345));
$data = $test->jsonSerialize();
echo $data->_id;
echo $data->filename;
Will output this:
12345
myfile
Another way would be:
json_encode( $bsonDoc->getArrayCopy() );
I had the same problem and this is how I accessed the values inside. This works with find.
foreach ($result as $entry) {
echo $entry['_id'], $entry['val1'], ['val2'];
}
Hope this helps someone.
I'm trying to loop through some JSON data and pull out specific values. Here is the JSON data and the partially working code.
$jsondata = '
[
{
"id" : "421356",
"trip_update" : {
"trip" : {
"trip_id" : "421356",
"start_time" : "12:05:00",
"start_date" : "20130926",
"route_id" : "15"
},
"stop_time_update" : {
"stop_sequence" :70,
"departure" : {
"delay" : 240,
"time" : 1380215057
},
"stop_id" : "6090"
},
"stop_time_update" : {
"stop_sequence" :71,
"departure" : {
"delay" : 240,
"time" : 1380215075
},
"stop_id" : "6095"
}
}
}]';
$result = json_decode($jsondata);
foreach($result as $value) {
echo "trip_id: ".$value->trip_update->trip->trip_id;
if (gettype($value->trip_update ) == "object") {
foreach($value->trip_update as $item) {
echo " - stop_sequence: ".$item->stop_sequence;
}
}
}
I can get the first level of data under 'trip_update->trip'. But there can be any number of 'stop_time_update' data within 'trip_update' as well. Since this data relates to the trip_update data, I need to loop through it and correlate it.
The end goal is to save this data to a database (not shown in the code), so for clarity, this would be the simplified 2 rows of DB data I would like to save in this example:
trip_id,stop_sequence
421356,70
421356,71
There can be any number of stop_sequences in the source data.
Here is an interactive link to the code for you to edit or mess with:
http://sandbox.onlinephpfunctions.com/code/f21ca8928da7de3e9fb351edb075d0a446906937
You might get better results if you write your own parser or use a stream-parser with callbacks. Here's a PHP implementation of such a parser that works with callbacks. So instead of reading the whole JSON data into memory, the parser will read the data in chunks and notify your "listener-class" whenever a new object starts or a property was read in etc. By doing this, you should get separate callback events for each stop_time_update property instead of just one value in the parsed array.
Very similar to what SAX is for XML.
Hi maybe you can change the name.
function next_update($coincidencias){
$replace=$coincidencias[0].$GLOBALS["json_stop_time_update"]++;
return $replace;
}
$result= preg_replace_callback("/stop_time_update/","next_update",$jsondata);
$result = json_decode($result);
You should rework your JSON - you have multiple keys with the same name, try to do print_r($result) to see what I am talking about - PHP will override the "stop_time_update" key time after time and you will be able to access only the last entry. Instead, you should organize your JSON like that:
[
{
"id" : "421356",
"trip_update" : {
"trip" : {
"trip_id" : "421356",
"start_time" : "12:05:00",
"start_date" : "20130926",
"route_id" : "15"
},
"stop_time_update" : [{
"stop_sequence" :70,
"departure" : {
"delay" : 240,
"time" : 1380215057
},
"stop_id" : "6090"
}, {
"stop_sequence" :71,
"departure" : {
"delay" : 240,
"time" : 1380215075
},
"stop_id" : "6095"
}]
}
}]
then you will be able to iterate through your data like this:
foreach($result[0]->trip_update->stop_time_update as $update)
{
$time = $update->departure->time;
...
}
If you cannot change the data structure, then what probably could help you is a PULL parser - one that does not return parsed data structure, but allows you to use a data stream instead - this way you could iterate over each node. The only one I managed to find is an extension to PHP:
https://github.com/shevron/ext-jsonreader
Check the usage section.
This JSON response is invalid because it contains duplicate keys but JSON doesn't allow duplicate keys.
You should contact the service you're trying to request this response from.
If you have a valid JSON response then you can decode it using the json_decode function which returns an object or an array (depends on the second parameter);
You cannot use a JSON parser for this as it will always overwrite the first element due to the same keys. The only proper solution would be asking whoever creates that "JSON" to fix his code to either use an array or an object with unique keys.
Another option is to write your own decoder function for parse it
I’m working on my master thesis where one of my goals is to run tests and experiments against the CouchDB database and tune the performance.
To do that I need some test data. I’ve created a piece of php code to generate some simple relational data for a MySQL database. The tables are:
Customer
Product
Brand
Color
Checkout
I’ve made some relations between for example Product and Colorid and Brandid and in the Checkout table I’ve a relation to Customerid and Productid.
I want to export this entirely data structure and the data with its relations to a JSON format for CouchDB.
So I’ve a JSON string which should contain each customer with its attributes and its purchase with all the parameters for this product, and so on.
I’m thinking that it would look something like:
{
"customer": {
"customerid" : "1",
"firstname" : "somefirstname",
"lastname" : "somelastname",
"email" : "my#mail.com",
"country" : "USA",
"datecreated" : "11111111111111"
}
"purchase" : {
"purchaseid" : "1",
"product": {
"productname" : "mightymouse",
"productcolor": "blue",
"productbrand" : "Apple",
"productprice" : "200",
"checkoutdate" : "1111111111112"
}
"purchaseid" : "2",
"product": {
"productname" : "something nice",
"productcolor": "yellow",
"productbrand" : "Google",
"productprice" : "5000",
"checkoutdate" : "11111111113333"
}
}
}
It’s probably not the right data structure I’ve shown but it something like that.
Can this be done in PHP and if so, how do I create this kind of “CouchDB” ready JSON strings??
If I haven’t explained myself clearly, please let me know.
Thank you
Sincere
- Mestika
PHP has function json_encode, you can use it to convert any PHP object to its JSON representation (and json_decode to convert JSON string to object).
So:
Use PHP database functions to read data from database.
Create object of stdClass:
$data = new stdClass;
Fill this object with properties read from database like this:
$customer = new stdClass;
$customer->customerid = "1"
...
$data->customer = $customer;
Encode generated object with json_encode.