How to access Multi Dimension Arrays/Arrays of Arrays [duplicate] - php
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 8 months ago.
I'm just trying to get into PHP and understand the core concepts, so have been messing around with arrays, jsons, etc. For this, I've tried everything, yet I cannot get to access the "Name" component of my Json. I recieve it from a CURL HTTP Request, decode it from a json then attempt to go from there. The JSON looks like:
[
{
"food1": "blah",
"food2": "blah",
"food3": "blah"
},
{
"food1": "blah",
"data": [
{
"name": "I need to access this",
"name2": "Another name"
}
]
}
]
I've tried $Result[0]["data"]["name"], $result[0][1]["data"]["name"] and plenty more combinations of that kind of nature, yet still haven't been able to figure it out. Any help would be greatly appreciated, thanks. :)
In your specific example you'd use $array[1]['data'][0]['name']
A breakdown of your array:
[
// this is the 0th element
{
"food1": "blah",
"food2": "blah",
"food3": "blah"
},
// this is the 1st element
{
"food1": "blah",
// 1st element's data property
"data": [
// 1st element's data property's 0th element
{
// [1]st element's [data] property's [0]th element's [name] property
"name": "I need to access this",
"name2": "Another name"
}
]
}
]
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
Targeting object within array JSON Steam API
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'];
find() query MongoDB for php
Hi i am using mongoDb for my new project. I am trying to find values from mongodb database. My mongoDB database collection name is: test and json format is below { "College": [ { "name": "tamy", "roll_no": "1" }, { "name": "abhi", "roll_no": "2" }, { "name": "jack", "roll_no": "3" } ], "School": [ { "name": "zack", "roll_no": "1" }, { "name": "mac", "roll_no": "2" }, { "name": "john", "roll_no": "3" } ] } **And i want to find the name:abhi from test collection ** and my mongodb find query in php $criteria = array( 'College'=> array( 'name'=> 'abhi' )); $cursor = $collection->find($criteria); but its not returning any value. if i am displaying in php by using print_r. print_r(iterator_to_array($cursor)); displaying empty array() I need output like this: name : jack roll_no : 3 plz help me..
The key "College" is an array, your trying to treat it as a "subdocument" (but that wouldnt allow for multiple colleges to be stored) You want the elemMatch keyword here I believe: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/ EDIT: After looking at this again, I think you have your structure a little out of whack. How many "students" will there be per college or school? Keep in mind each parent document can not exceed 10mb, and when you select a document, the entire document must be sent back across the connection (unless you are using aggregate or map/reduce. I would think you may want to have a collection of Persons and then a key associating a person to... something else.
Access JSON_encode array objects
I have a problem access values from array objects. From PHP I send my array of objects like this initiate_data(".json_encode($my_array)."); From javascript to check the array I have this code function initiate_data(my_array){ window.alert(my_array);} The data I have is {'name':'name1','surname':'surname1','email':'email1'},{'name':'name2','surname':'surname2','email':'email2'},{'name':'name3','surname':'surname3','email':'email3'} I am also able to access the first object window.alert(my_array[0]); The result is {'name':'name1','surname':'surname1','email':'email1'} My problem is that I cannot access name from the object. I have tried (my_array[0].name) and I get undefined I googled for the solution but I cannot get a solution specific to my problem when I try to access my_array[0][0] the result { Thank you for your help thus far console.log gives me this ["{"rec":"1","name":"Home","code":"mmenu_home","type":"1","level":"0","default_view":"show_post"}", "{"rec":"2","name":"Home","code":"mmenu_home","type":"2","level":"0","default_view":"show_post"}", "{"rec":"3","name":"Home","code":"mmenu_home","type":"3","level":"1","default_view":"show_post"}", "{"rec":"4","name":"Home","code":"mmenu_home","type":"3","level":"2","default_view":"show_post"}", "{"rec":"5","name":"Home","code":"mmenu_home","type":"3","level":"3","default_view":"show_post"}", "{"rec":"6","name":"Home","code":"mmenu_home","type":"3","level":"4","default_view":"show_post"}", "{"rec":"7","name":"Home","code":"mmenu_home","type":"3","level":"5","default_view":"show_post"}", "{"rec":"8","name":"Home","code":"mmenu_home","type":"3","level":"6","default_view":"show_post"}", "{"rec":"9","name":"Home","code":"mmenu_home","type":"4","level":"0","default_view":"show_post"}", "{"rec":"10","name":"Opporunities","code":"mmenu_op…":"1","level":"0","default_view":"show_opp_tips"}", "{"rec":"11","name":"Careers","code":"mmenu_careers…e":"1","level":"0","default_view":"show_careers"}", "{"rec":"12","name":"Tertiary","code":"mmenu_tertia…":"1","level":"0","default_view":"show_tertiary"}", "{"rec":"13","name":"News","code":"mmenu_news","type":"1","level":"0","default_view":"show_news"}", "{"rec":"14","name":"News","code":"mmenu_news","type":"2","level":"0","default_view":"show_news"}", "{"rec":"15","name":"News","code":"mmenu_news","type":"3","level":"1","default_view":"show_news"}", "{"rec":"16","name":"News","code":"mmenu_news","type":"3","level":"2","default_view":"show_news"}", "{"rec":"17","name":"News","code":"mmenu_news","type":"3","level":"3","default_view":"show_news"}", "{"rec":"18","name":"News","code":"mmenu_news","type":"3","level":"4","default_view":"show_news"}", "{"rec":"19","name":"News","code":"mmenu_news","type":"3","level":"5","default_view":"show_news"}", "{"rec":"20","name":"News","code":"mmenu_news","type":"3","level":"6","default_view":"show_news"}", "{"rec":"21","name":"News","code":"mmenu_news","type":"4","level":"0","default_view":"show_news"}", "{"rec":"22","name":"Profile","code":"mmenu_profile…e":"1","level":"0","default_view":"show_profile"}", "{"rec":"23","name":"Profile","code":"mmenu_profile…e":"2","level":"0","default_view":"show_profile"}", "{"rec":"24","name":"Profile","code":"mmenu_profile…e":"3","level":"1","default_view":"show_profile"}", "{"rec":"25","name":"Profile","code":"mmenu_profile…e":"3","level":"2","default_view":"show_profile"}", "{"rec":"26","name":"Profile","code":"mmenu_profile…e":"3","level":"3","default_view":"show_profile"}", "{"rec":"27","name":"Profile","code":"mmenu_profile…e":"3","level":"4","default_view":"show_profile"}", "{"rec":"28","name":"Profile","code":"mmenu_profile…e":"3","level":"5","default_view":"show_profile"}", "{"rec":"29","name":"Profile","code":"mmenu_profile…e":"3","level":"6","default_view":"show_profile"}", "{"rec":"30","name":"Profile","code":"mmenu_profile…e":"4","level":"0","default_view":"show_profile"}", "{"rec":"31","name":"SMS","code":"sms_send_function…"type":"3","level":"2","default_view":"sms_home"}", "{"rec":"32","name":"SMS","code":"sms_send_function…"type":"3","level":"5","default_view":"sms_home"}", "{"rec":"33","name":"SMS","code":"sms_send_function…"type":"3","level":"6","default_view":"sms_home"}", "{"rec":"34","name":"Learners","code":"learners_mme…":"3","level":"2","default_view":"view_learners"}", "{"rec":"35","name":"Learners","code":"learners_mme…":"3","level":"3","default_view":"view_learners"}", "{"rec":"36","name":"Learners","code":"learners_mme…":"3","level":"4","default_view":"view_learners"}", "{"rec":"37","name":"Learners","code":"learners_mme…":"3","level":"5","default_view":"view_learners"}", "{"rec":"38","name":"Learners","code":"learners_mme…":"3","level":"6","default_view":"view_learners"}", "{"rec":"39","name":"Parents","code":"parents_mmenu…e":"3","level":"2","default_view":"view_parents"}", "{"rec":"40","name":"Parents","code":"parents_mmenu…e":"3","level":"3","default_view":"view_parents"}", "{"rec":"41","name":"Parents","code":"parents_mmenu…e":"3","level":"4","default_view":"view_parents"}", "{"rec":"42","name":"Parents","code":"parents_mmenu…e":"3","level":"5","default_view":"view_parents"}", "{"rec":"43","name":"Parents","code":"parents_mmenu…e":"3","level":"6","default_view":"view_parents"}", "{"rec":"44","name":"Staff","code":"staff_function"…:"3","level":"2","default_view":"staff_view_all"}", "{"rec":"45","name":"Staff","code":"staff_function"…:"3","level":"5","default_view":"staff_view_all"}", "{"rec":"46","name":"Staff","code":"staff_function"…:"3","level":"6","default_view":"staff_view_all"}", "{"rec":"47","name":"SGB","code":"sgb_home","type":"3","level":"2","default_view":"sgb_view_all"}", "{"rec":"48","name":"SGB","code":"sgb_home","type":"3","level":"5","default_view":"sgb_view_all"}", "{"rec":"49","name":"SGB","code":"sgb_home","type":"3","level":"6","default_view":"sgb_view_all"}", "{"rec":"50","name":"Photos","code":"photos_mmenu",…vel":"2","default_view":"view_all_websitephotos"}", "{"rec":"51","name":"Photos","code":"photos_mmenu",…vel":"5","default_view":"view_all_websitephotos"}", "{"rec":"52","name":"Photos","code":"photos_mmenu",…vel":"6","default_view":"view_all_websitephotos"}", "{"rec":"53","name":"Departments","code":"mm_depart…3","level":"2","default_view":"view_departments"}", "{"rec":"54","name":"Departments","code":"mm_depart…3","level":"5","default_view":"view_departments"}", "{"rec":"55","name":"Departments","code":"mm_depart…3","level":"6","default_view":"view_departments"}", "{"rec":"56","name":"Academic","code":"mm_academic"…":"3","level":"2","default_view":"view_academic"}", "{"rec":"57","name":"Academic","code":"mm_academic"…":"3","level":"5","default_view":"view_academic"}", "{"rec":"58","name":"Academic","code":"mm_academic"…":"3","level":"6","default_view":"view_academic"}", "{"rec":"59","name":"Term","code":"mm_term","type":"1","level":"0","default_view":"view_term"}", "{"rec":"60","name":"Term","code":"mm_term","type":"2","level":"0","default_view":"view_term"}", "{"rec":"61","name":"Term","code":"mm_term","type":"3","level":"1","default_view":"view_term"}", "{"rec":"62","name":"Term","code":"mm_term","type":"3","level":"2","default_view":"view_term"}", "{"rec":"63","name":"Term","code":"mm_term","type":"3","level":"3","default_view":"view_term"}", "{"rec":"64","name":"Term","code":"mm_term","type":"3","level":"4","default_view":"view_term"}", "{"rec":"65","name":"Term","code":"mm_term","type":"3","level":"5","default_view":"view_term"}", "{"rec":"66","name":"Term","code":"mm_term","type":"3","level":"6","default_view":"view_term"}", "{"rec":"67","name":"Sports","code":"mm_sports","type":"1","level":"0","default_view":"view_sports"}", "{"rec":"68","name":"Sports","code":"mm_sports","type":"2","level":"0","default_view":"view_sports"}", "{"rec":"69","name":"Sports","code":"mm_sports","type":"3","level":"1","default_view":"view_sports"}", "{"rec":"70","name":"Sports","code":"mm_sports","type":"3","level":"2","default_view":"view_sports"}", "{"rec":"71","name":"Sports","code":"mm_sports","type":"3","level":"3","default_view":"view_sports"}", "{"rec":"72","name":"Sports","code":"mm_sports","type":"3","level":"4","default_view":"view_sports"}", "{"rec":"73","name":"Sports","code":"mm_sports","type":"3","level":"5","default_view":"view_sports"}", "{"rec":"74","name":"Sports","code":"mm_sports","type":"3","level":"6","default_view":"view_sports"}", "{"rec":"75","name":"Timetable","code":"mm_timetabl…:"1","level":"0","default_view":"view_belltimes"}", "{"rec":"76","name":"Timetable","code":"mm_timetabl…:"2","level":"0","default_view":"view_belltimes"}", "{"rec":"77","name":"Timetable","code":"mm_timetabl…:"3","level":"1","default_view":"view_belltimes"}", "{"rec":"78","name":"Timetable","code":"mm_timetabl…:"3","level":"2","default_view":"view_belltimes"}", "{"rec":"79","name":"Timetable","code":"mm_timetabl…:"3","level":"3","default_view":"view_belltimes"}", "{"rec":"80","name":"Timetable","code":"mm_timetabl…:"3","level":"4","default_view":"view_belltimes"}", "{"rec":"81","name":"Timetable","code":"mm_timetabl…:"3","level":"5","default_view":"view_belltimes"}", "{"rec":"82","name":"Timetable","code":"mm_timetabl…:"3","level":"6","default_view":"view_belltimes"}"] Additional Info** The php class implements JsonSerializable and I have created a array of the object, I hope this will help in clarifying my problem Temporary Fix Although they might be a better way to do it, this is what I have done to solve the problem var my_obj = JSON.parse(my_array[0]); Now I am able to access name console.log(my_obj.name); Gives me name1 Temporary Fix, Until I am able to pass all the array to a variable.
Looks like your $my_array contains json strings: $my_array = array( '{"name":"name1","surname":"surname1","email":"email1"}', '{"name":"name2","surname":"surname2","email":"email2"}', '{"name":"name3","surname":"surname3","email":"email3"}' ); If it is the case, you can create javascript array of it by simple implode and add brackets: initiate_data([".implode(',',$my_array)."]);
is the json well encoded?? http://jsonlint.com/ { "obj1": { "name": "name1", "surname": "surname1", "email": "email1" }, "obj3": { "name": "name1", "surname": "surname1", "email": "email1" }, "obj2": { "name": "name1", "surname": "surname1", "email": "email1" } }
PHP/MongoDB: update a value in an array
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.