Unable to fetch values from json array tree in codeigniter - php
I have following array tree in json which is passed to view in a variable
[{
"root":"0",
"id":"19",
"name":"Rose",
"childs":[{
"root":"19"
"id":"22",
"name":"Ceema",
"childs":[{
"root":"22",
"id":"49",
"name":"Chandar"
},
{
"root":"22",
"id":"50",
"name":"Carol"
}]
},
{
"root":"19",
"id":"23",
"name":"Ben"
}]
}]
now i want that at first it displays the name of array with root 0, when we click on that name, it shows the name contained in arrays within child(if it has any).
M not so good with json, so please help!
Use json_decode() function in php or if you want to do it in javascript JSON.parse
This will give you result in array and rest things you need to do or find the code for it.
Related
How can I Iterate through PHP multi-dimension array that has label -> value structure
New to PHP (from C#). I have an array ($metaarray), which if I json_encode() to the screen, it has this value: [ { "measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31" },{ "measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12" },{ "measure":"","record":"","latestres":null,"datet":"2022-09-12" },{ "measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12" },{ "measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12" },{ "measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12" } ] Is there an easy way for me to iterate through the metaarray - or to easily reference a record - eg. I would normally do something like: $latestres = $metaarray[0][2]; ...which should be "6870" - however it doesn't return any result when I do that. Is there a way I can easily reference a particular value (eg. first record, "latestres" or 3rd value) in the above array?
I don't know if this helps you, but $data[2] does not represent third item in an array, unless the array happens to be created linearly (called a list). In PHP, 2 is actually the key to a map (name/value pair). So unless there is actually a key with that index, you can't access it. You can see a demo of what I'm talking about here. You can get around the feature/limitation by using one of the tricks from this answer: https://stackoverflow.com/a/24825397/231316 function getNthItemFromArray(array $array, int $idx) { return $array[array_keys($array)[$idx]]; } Obviously you'd add some guards. As everyone notes, you should really start with your data before the encode. However, assuming that for whatever you have a JSON string, you can tell the decoder to give you an associative array instead of an object. Putting that all together you could do something like: $json = <<<EOT [ { "measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31" },{ "measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12" },{ "measure":"","record":"","latestres":null,"datet":"2022-09-12" },{ "measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12" },{ "measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12" },{ "measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12" } ] EOT; $decoded = json_decode($json, true); echo getNthItemFromArray($decoded[0], 2); function getNthItemFromArray(array $array, int $idx) { return $array[array_keys($array)[$idx]]; } Demo here: https://3v4l.org/POdma
How to search through unknown property name in database with Laravel
I'm trying to search database with json contains method of laravel. Here is my JSON of one database line: { "row": { "1": { "ID":"110555175667" }, "2": { "ID":"11023235667" }, "3": { "ID":"11001414141667" }, "4": { "ID":"11023235667" }, "5": { "ID":"1100012222225667" }, } } I want to search ID, but as you see there are numbers as properties. In example I want to find 11023235667. I've tried it like that: ->whereJsonContains('json', [['row' => ['1' => ['ID' => '11023235667']]]]) But it didn't worked. How can I do it? EDIT: I have also tried this: ->whereRaw('JSON_CONTAINS(json, "$.row.*.ID", "11023235667")') I know the property of row must be JSON array to accomplish to match the id, but it has been set as JSON object
The usage of JSON_CONTAINS() accepts a JSON document as its second argument, not a path. You could use that path to extract the ID's into an array: SELECT JSON_EXTRACT(json, '$.row.*.ID') FROM ... +--------------------------------------------------------------------------------------+ | ["110555175667", "11023235667", "11001414141667", "11023235667", "1100012222225667"] | +--------------------------------------------------------------------------------------+ Using this, you can search the resulting array: SELECT ... FROM mytable WHERE JSON_SEARCH(JSON_EXTRACT(json, '$.row.*.ID'), 'one', '11023235667') IS NOT NULL; You would need to do this using whereRaw() in Laravel, because Laravel doesn't have a builtin query builder function for this expression. Tip: As soon as you reference a JSON column in the WHERE clause of an SQL query, your query becomes harder to write, and harder to optimize. This should be a red flag indicating your design is wrong. You would be better off storing data in normal rows and columns, not JSON.
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'];
PHP JSON object nested loop data syntax
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
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" } }