I have this array in PHP
<?php
$data = array();
$data[0] = array('year' => 2001, 'month' => array(
'January' => array('val1' => 1000, 'val2' => 2000),
'February' => array('val1' => 1000, 'val2' => 2000)
)
);
$data[1] = array('year' => 2002, 'month' => array(
'January' => array('val1' => 3000, 'val2' => 4000),
'February' => array('val1' => 6000, 'val2' => 7000)
)
);
echo json_encode($data);
?>
I am trying to access from javascript to the properties of this array from javascript, but I have not reached.
I tried this
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'ajax1.php',
type: 'GET',
dataType: 'json'
}).done(function (data) {
var i = 0;
for (i in data) {
$('#year').append('<b>'+data[i].year+'</b>'+':<br/>');
var x=0;
for(x in data[i].month){
$('#year').append(data[i].month[x] +'<br/>');
x++;
}
i++;
}
});
});
</script>
<title>Graphs</title>
</head>
<body>
<div id="year">
</div>
</body>
</html>
I get the access to the year, but not the other properties.
Prints the following:
2001:
[object Object]
[object Object]
2002:
[object Object]
[object Object]
since each month is an array - won't you need an extra loop to get the values within that months array. the outcome of which would be:
$('#year').append(data[i].month[x][0] //= val1 within month[x]
$('#year').append(data[i].month[x][1] //= val2 within month[x]
so you would need three nested loops:
//pseudo code including a new loop "z"
[i] to get the year;
[x] to get each month within year[i];
[z] to get each value within month[x];
After decode a JSON, created with PHP json_encode, non numeric arrays are converted in Javascript Objects. If you need array try with numeric keywords.
Some browsers like chrome, sort alphabetically the object keywors. If you are thinking iterate the object, you need to known this before.
A suggestion: use $.each i jQuery to iterate arrays or objects is more simple.
$.each(data, function(key, value){
...
});