Accessing JSON encoded MuliDimensional array using jQuery - php

I have an multidimensional array
$array = array(
"Level1"=>array(
"Level11"=>array(
"level111"=>'value1',
"level112"=>'value2',
),
"Level12"=>array(
"level121"=>'value1',
"level122"=>'value2',
),
),
"Level2"=>array(
"Level21"=>array(
"level211"=>'value1',
"level212"=>'value2',
),
"Level22"=>array(
"level221"=>'value1',
"level222"=>'value2',
),
)
);
echo json_encode($array);
This encoded JSON is sent after receiving AJAX POST request using jQuery.
$.post(
'mypage.php',
{
param1: value1,
param2: value2
},
function(data) {
//Now I can access the 1st level JSON value easily like
alert(data.Level1);
// But
// I am trying to access the values like
alert(data.Level1.Level11.level112); //which is not possible
},
"json"
);
If you have understood my question, do you know how I could tackle this problem.

Ok, my guess: You use capital letters in some of your keys in PHP but not in JS. Your line should be:
data.Level1.Level11.level112
Note that it is Level1 with captial L, not level1.
DEMO

Related

add value to JSON of title

I search a lot in stack and google try to find the answer which seems to be easy but I'm still stuck with it
I write a code to encode json with values I wanted from . and I would like to add a key / value to the JSON
the JSON is as following structure
{
- files: [
{
title: "works",
- tracks: [
{
title: "File",
format: "mp3"
}
]
},
-{
title: "season1",
tracks: [
{
title: "Button-1",
format: "wav"
},
-{
title: "Beep-9",
format: "wav"
}
]
}
]
}
I want to add to that a key and its value at the beginning to the json as properties under the title files , I mean that can be read by code as
json[files][new_key]
I tried to set that value like this
$json['new_key'] = "new_value";
but this causes adding numbers to the arrays in json , I don't why they numbered
this numbers affect my reading way of the json as JSONModel in my iOS app
so , I hope you can help me
thanks in advance
Assuming that the new value you want to add varies by file, you would need to loop through $json[files] and insert them per key/value pair.
<?php
for($i=0; $i<count($json); $i++)
$json[files][$i]["new_key"] = "value";
?>
I'm still not sure what you have exactly, but it seems you are trying to manipulate the json string.
If done correctly, that is probably the most efficient solution, but what you could also do is:
use json_decode to generate an array from your json string;
locate the correct section / sub-array where you want to add your data;
use array_unshift to prepend your new key - value pair;
use json_encode to generate a json string from your complete array.
The reason you're getting numbers appearing is because you're adding a key to an array (which functions more or less as a list in JS). So before you basically have the object "files" as a list of objects zero-indexed like any other JS array. When you add the key, JS simply adds your key to the end of your present keys (in your case 0 and 1).
It seems like you have a list of multimedia objects where each has a title and a list of tracks. The most straightforward way to solve your issue would be as follows:
$fileItem['title'] = 'works';
$fileItem['tracks'] = array(
array(
'title' => 'File',
'format' => 'mp3'
)
);
$json['files'][] = $fileItem;
$fileItem['title'] = 'season1';
$fileItem['tracks'] = array(
array(
'title' => 'Button-1',
'format' => 'wav'
),
array(
'title' => 'Beep-9',
'format' => 'wav'
)
);
$json['files'][] = $fileItem;
Then you JSON encode it and return it as you normally would. You can put the above in a loop as well. I lack enough context to recommend exactly how.

Updating Flot PHP, AJAX, JSON

I am having some trouble updating a Flot bar chart from an Ajax request to a PHP script that returns JSON data.
The PHP script is:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => "Group One,80,Group Two,10"
);
echo json_encode($vars);
This is returned to a variable 'series'
var data = [series.series];
This outputs to the console:
Group One,80,Group Two,10
I also have a commented out variable which is:
//var datatwo = [ ["Group One", 80], ["Group Two", 10] ];
This also outputs to the console
Group One,80,Group Two,10
The actual javascript to create the graph is
$.plot("#group-month-graph", [data], options);
The options are assigned at another location of the script.
Im trying to figure out what Im doing wrong as when I alert the returned data or output it to the console the values are identical, however the returned data will not draw the graph whereas if I use the commented out value it does.
Hope that makes sense. I have cut down the full script as I dont think that the issue lies anywhere else.
You are returning a String while the plugin is expecting an Array. You should return [["Group One",80],["Group Two",10]]
Change your php series structure to:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => array(array("Group One",80),array("Group Two",10))
);
Also, you should be getting the series array using data and not [data]
$.plot("#group-month-graph", data, options);

jQuery-UI Autocomplete Using URL Source Works With Array of Strings But Not Array of Objects

Using jQuery 1.7.2 and jQuery UI 1.8.18. If I use local data for the source attribute, everything works as expected. According to the documentation, a source array can be an array of string values or an array of objects:
Array: An array can be used for local data. There are two supported
formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
Additionally, the source attribute can be a URL that responds with JSON data formatted as shown above:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
If my JSON responder returns a simple array of strings, autocomplete works exactly as it should. If, however, my JSON responder returns an array of objects formatted as above, the request is made to the URL but the dropdown list is never populated. The JavaScript console shows no errors.
The autocomplete invocation looks like this:
var source_url = '/json/codes.php?type=globalcode&cid=25';
$('.gcode').autocomplete({
minLength: 2,
source: source_url
});
The responder is written in PHP. It is just a stub until I get this problem solved:
header('Content-Type: application/json, charset=UTF-8');
...
if( !$_REQUEST['type'] || !$_REQUEST['cid'] ){
echo('[]');
return false;
}
if( $_REQUEST['type'] == 'globalcode' ){
$cid = sprintf("%d", $_REQUEST['cid']);
$stub = "[ { label: 'Label for 1234', value: '1234' }, { label: 'Label for 5678', value: '5678' } ]";
echo( $stub );
return false;
}
Again, it works with both kinds of arrays when the data is local and it works with an array of string values when the data is remote. When the data is a remote array of objects, the list is never populated and JavaScript throws no errors.
You have invalid JSON, this is never logged in the console.
JSON cannot have single quotes, use double quotes, also use JSONLint to check your JSON.
This is the valid version of your JSON:
[
{
"label": "Labelfor1234",
"value": "1234"
},
{
"label": "Labelfor5678",
"value": "5678"
}
]
You could use json_encode() instead
$stub = array(
array(
"label"=>"Labelfor1234",
"value"=>"1234"
),
array(
"label"=>"Labelfor5678",
"value"=>"5678"
)
);
echo json_encode($stub);

Dynamically add data stored in php to nested json

I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of combinations and nothing. Here is the json format:
var data = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
},{
name: " ",
desc: "Scoping",
values: [{
from: "/Date(1322611200000)/",
to: "/Date(1323302400000)/",
label: "Scoping",
customClass: "ganttRed"
}]
}, <!-- Somoe more data-->
}];
now I have all data in php db result. Here it goes:
$rows=$db->fetchAllRows($result);
$rowsNum=count($rows);
And this is how I wanted to create json out of it:
var data='';
<?php foreach ($rows as $row){ ?>
data['name']="<?php echo $row['name'];?>";
data['desc']="<?php echo $row['desc'];?>";
data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
}
However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?
First of all you're adding properties to string instead of building object. If you really want to do that this way:
var data = [], row;
<?php foreach ($rows as $row) : ?>
row = {};
row.name ="<?php echo $row['name'];?>";
row.desc ="<?php echo $row['desc'];?>";
row.values = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
data.push(row);
<?php endforeach; ?>
Anyway it is unsafe (and result is normal JS code, not proper JSON object - but as you're assigning it to variable then I suppose it does not have to be in strict JSON format)
Better approach would be to build data structure in PHP and use json_encode function to generate JSON data for JavaScript:
<?php
$data = array();
foreach ($rows as $row) {
$data[] = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(array(
'from' => '/Date('.$row['from'].'>)/',
'to' => '/Date('.$row['to'].')/',
'label' => $row['label'],
'customClass' => 'ganttOrange',
))
);
}
?>
var data = <?php echo json_encode($data); ?>;
Quick Answer
As stated previously, this problem is easily resolved using the PHP json_encode function.
The trick to understanding how to do this easily is to understand the composite data structure that you are trying to work with.
Overview
What you are dealing with is a general programming concept called a "composite data structure". The trick to understanding this is to realize that the PHP and the JavaScript that you are attempting to manage are just two different representations of the exact same thing.
Once this concept sinks in, it will be easy to relate to what the users Musa and dev-null-dweller have already explained.
The straightforward way to solve this issue is to simply build a composite data structure in PHP and then translate it into JSON (aka JavaScript) using the built-in native methods of PHP's json_encode and json_decode.
Instead of doing all the statements, you should treat each $row as a composite data structure and use the PHP json functions.
The following example should give you a head start, simply compare it to the data you are trying to work with and change accordingly.
Example 001
// This is a PHP composite data structure [ a nested array ]
// represented in PHP. When you run this code you will get the
// output of Result 001
$user_profile = Array(
main => Array(
first_name => "_blank_",
last_name => "_blank_",
sex => "_blank_",
age => "_blank_",
),
guardian => Array(
first_name => "",
last_name => "",
),
children => Array(
0 => Array(
first_name => "Sally",
last_name => "Shaw",
),
1 => Array(
first_name => "Scott",
last_name => "Shaw",
),
),
);
// This is some sample PHP code you can use to modify
// the composite data structure (modify the "_blank_" values)
//
$user_profile["main"]["first_name"] = "Archibald";
$user_profile["main"]["last_name"] = "Shaw";
$user_profile["main"]["age"] = "33";
$user_profile["main"]["sex"] = "male";
// This is some sample PHP code you can use to modify
// the composite data structure (add a new child)
//
$user_profile["children"][2] = Array();
$user_profile["children"][2]["first_name"] = "Carrie";
$user_profile["children"][2]["last_name"] = "Shaw";
// This is the PHP code you can use to transform from PHP to JSON
$result = json_encode( $user_profile );
print_r( $result );
Result 001 (formatted for easy readability)
{
"main":{
"first_name":"Archibald",
"last_name":"Shaw",
"sex":"male",
"age":"33"
},
"guardian":{
"first_name":"",
"last_name":""
},
"children":[
{
"first_name":"Sally",
"last_name":"Shaw"
},
{
"first_name":"Scott",
"last_name":"Shaw"
},
{
"first_name":"Carrie",
"last_name":"Shaw"
}
]
}
Conclusion
Using the example above, you should first do a print_r of the PHP variable you are trying to work with and get an idea of the overall structure. Once you know this, it is an easy step to convert it to JSON using the built-in PHP json_encode function.
References
http://en.wikibooks.org/wiki/PHP_Programming/Data_Structures#The_Basics
http://en.wikipedia.org/wiki/Composite_type
var data=[];
<?php
foreach ($rows as $row)
{
$obj = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(
array(
"from" => "/Date({$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange",
)
)
);
$objJson = json_encode($obj);
echo "data.push({$objJson});\n";
}
?>
You should create the data structure in php and echo it out with json_encode.
<?php
$data = array();
foreach ($rows as $row){
$item = array();
$item['name']=$row['name'];
$item['desc']=$row['desc'];
$item['values']= array("from" => "/Date{$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange");
$data[] = $item;
}
echo "\nvar data = ".json_encode($data).";\n";

Access JSON array values?

eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:
$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data);
}
I'm left with the array parsedData which looks like this:
[
{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}
]
I've placed those arrays in an array named
var peopleArray= { people: [ parsedData ] };
So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:
alert (peopleArray.people[0].person1.name);
Whiched returns:
Uncaught TypeError: Cannot read property 'name' of undefined
How can I access those attributes?
Apart from the typo ("namn") the problem is you're putting an array inside an array:
var peopleArray = { people: [ parsedData ] };
Since parsedData is an array then what you end up with is a structure like this:
// peopleArray
{ people : [ [ { "person0" : ... }, ... ] ] }
// oops -----^
See the problem? Since parsedData is a already an array the correct code would be:
var peopleArray = { people: parsedData };

Categories