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.
Related
I have this json value that I want to be sorty but for some reason it's not working.
[
{
"id": 15028,
"order_id": 342,
"user_id": 3,
"status": "1",
"priority": "1",
"donedate": null,
"user": {
"id": 3,
"name": "Max"
}
},
{
"id": 15030,
"order_id": 341,
"user_id": 4,
"status": "2",
"priority": "1",
"donedate": null,
"user": {
"id": 4,
"name": "Jon"
}
}
]
This jSon structure is the result of Laravel eloquent object conversion using $object->toJson();
Now I keep this output in my Redis cache. What I want is to when the status and or priority of any order gets changed then I want to sort this jSon and store it back in Redis.
$order_list = collect($json_decoded_with_updated_values);
$order_list = $order_list->sortBy('status')->sortBy('priority');
Redis::set(\GuzzleHttp\json_encode($stich_list_in_collection));
Redis::set("orders_list", $orders_list, 302400);
However, I don't get a sort list. What I want to achieve is that, just like I would run two to three orderBy on an eloquent model like orderBy('status')->orderBy('priority')->get() .. I want to run the same two sortings on this json list.
Thanks in advance.
I figured it out. Actually we don't need to have a call-back as suggested by #brokedid. We can do it like following.
$order_list->sortBy('status')->sortBy('priority')->values()->all();
So I was missing the "->values()->all()" part. I hope if any one runs into the same problem in future, they can get a hint from this.
If you want to sort by multiple Fields, then you could try to sort with a callback-method:
$orderedList = $unorderedList->sortBy(function($item) {
return $item->priority.'-'.$item->status;
});
I wonder what's the result when you choose a different sort direction.
$order_list = $order_list->sortByDesc('status');
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
im trying to figure out what the easiest way would be. i have a to do an api call for data i get a json file in return but im trying to parse the data to php so that my website would just pull from the database. do i have to create all the same fields that the api call is using for instance name gender age height. and then do i name it something else so i can call from my webpage. because in order to get a nfl player it gives me a 16 digit code and i want it just to be say tom brady
i have used javascript to pull the data but dont know what to do from there
"players": [{
"name": "Kyle Rudolph",
"jersey": "82",
"last_name": "Rudolph",
"first_name": "Kyle",
"abbr_name": "K.Rudolph",
"preferred_name": "Kyle",
"birth_date": "1989-11-09",
"weight": 265.0,
"height": 78,
"status": "A01",
"id": "1059e9dc-97df-4643-9116-883a0573d8b1",
"position": "TE",
"birth_place": "Cincinnati, OH, USA",
"high_school": "Elder (OH)",
"college": "Notre Dame",
"college_conf": "Independent",
"rookie_year": 2011,
"draft": {
"year": 2011,
"round": 2,
"number": 43,
"team": {
"name": "Vikings",
"market": "Minnesota",
"alias": "MIN",
"id": "33405046-04ee-4058-a950-d606f8c30852"
}
},
John, you don't have to use the same names. Once your PHP receives data from the API, parse it into whatever names you want, ignore the values you don't need etc... For example, suppose the API gives you a first and last name, but in your database you only care about full name. As another example, if the API gives you player weight in pounds but you need it in kilograms:
$api_result = file_get_contents($url);
$api_data = json_decode($api_result);
$name = "$api_data->last, $api_data->first"
$weight = $api_data->weight * 0.454; //convert pounds to kg for storage
Now you can store $name and $weight in your DB as you like. When your website pulls data from your backend, the shape of the data produced by the API doesn't matter because you stored it in the shape that is most helpful to your application
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.
I have the following mongodb object:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"0": {
"toUname": "Eamorr3",
"fromUname": "Eamorr2",
"time": 1292606586,
"id": "ABCDZZZ",
"subject": "asdf",
"message": "asdf",
"read": 0 //I want to change this to 1!
},
"1": {
"toUname": "Eamorr1",
"fromUname": "Eamorr3",
"time": 1292606586,
"id": "EFGHZZZ",
"subject": "asdf2",
"message": "asdf2",
"read": 0
}
},
"uname": "Eamorr3"
}
How do I set "read" to 1 where id=ABCDZZZZ? I'm using PHP.
I've tried the following command:
$driverInboxes->update(array('uname'=>$uname),array('$set'=>array('messages'=>array('id'=>$id,'read'=>'1'))));
But when I do this, overwriting occurs and I get:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"id": "j7zwr2hzx14d3sucmvp5",
"read": "1"
},
"uname": "Eamorr3"
}
I'm totally stuck. Any help much appreciated.
Do I need to pull the entire array element, modify and and push it back in again?
Many thanks in advance,
If you read your command, you're actually saying: "UPDATE WHERE uname = Eamorr3 SET messages equal to this array (id=blah,read=1)"
When you do a $set on messages, you're basically instructing it to take your array as the new value.
However, it looks like you're trying to update a specific message as read which is just a little more complex. So there are two hurdles here:
1: You're actually updating messages.0.read
If you do array('$set' => array( 'messages.0.read' => 1 ) ), you will update the correct element. Follow that chain, messages is a javascript object and you want to update the property 0. The property 0 is itself a javascript object which contains the property read which you want to update.
Can you see how you're updating messages.0.read?
This brings us to problem #2.
2: the 0 is a problem for you
If you look at the way you've structured the data in Mongo, the messages object is really sub-par. The "0" and "1" are currently acting as "ids" and they're not very useful. Personally, I would structure your objects with the actual IDs in place of "0" or "1".
So your objects would look like the following:
{
"_id": ObjectId("4d0b9c7a8b012fe287547157"),
"messages": {
"ABCDZZZ": {
"toUname": "Eamorr3",
"fromUname": "Eamorr2",
"time": 1292606586,
"subject": "asdf",
"message": "asdf",
"read": 0 //I want to change this to 1!
}
},
"uname": "Eamorr3"
}
Now you're update command becomes this:
array('$set' => array( 'messages.ABCDZZZ.read' => 1 ) )
This structure makes it much easier to update a specific message or a specific portion of a message.
If you want to keep the array structure for various purposes, you can use the Positional operator. This enables you to take advantage of array features ($pop,$push,etc) while simultaneously being able to update elements which are in an unknown array position.