从PHP中回显的json编码数组中迭代javascript对象

I'm trying to get values from a PHP array in Javascript and populate a chart.

The problem is I believe that the javascript variable is not receiving the values.

I tried printing out the values, but nothing happens. Also it shows as object instead of an array, i don't know if it's suppose to be like that.

Any help will be greatful.

The PHP array when printed out:

print_r("<pre>"); 
print_r($exam_grades);
print_r("</pre>");

Array
(
    [History] => 70
    [Sociology] => 40
    [Psychology] => 32
    [Criminology] => 64
)

JS:

var exam_grades = <?php echo json_encode($exam_grades );?>;
alert(exam_grades.length); // this shows as undefined
for (var i = 0; i < exam_grades.length; i++) {

    // do something      
}

As an alternative, you could also use for in to iterate thru the object:

<?php $exam_grades = array('History' => 70, 'Sociology' => 40, 'Psychology' => 32, 'Criminology' => 64); ?>
<script type="text/javascript">
var exam_grades = <?php echo json_encode($exam_grades); ?>;
for(var key in exam_grades) {
    var value = exam_grades[key];
    console.log(key + ': ' + value);
}
</script>

Sample Output

Your problem is that the JS Array haven't associative indexes, so your PHP array turns into a JS object. You could try to rewrite your PHP array like this:

$grades = [
    ['exam' => 'History', 'grade' => 70],
    ['exam' => 'Sociology', 'grade'  => 40],
    ['exam' => 'Psychology', 'grade'  => 32],
    ['exam' => 'Criminology', 'grade'  => 64]
];

Then you can iterate fine on JS, after the json_encode.

The variable is an object (because the array in PHP has string keys), which you can iterate over using Object.keys():

Object.keys(exam_grades).forEach(function(key) {
    console.log(key + ': ' + exam_grades[key]);
});

Do note that object properties in JavaScript aren't ordered by definition, so if that's important, you should consider creating a numerically indexed array in PHP.

A php associative array will json encode into a javascript object, because javascript does not have true associative arrays as php does. The length is undefined because javascript objects do not have a native length property. To loop thru the object you can do:

for (var key in exam_grades) 
{ if (exam_grades.hasOwnProperty(key)) { 
    console.log(key + " -> " + exam_grades[key]);
    }
}