dth981485742
2015-01-14 00:51 阅读 57

从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      
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    doubengman2072 doubengman2072 2015-01-14 01:01

    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

    点赞 评论 复制链接分享
  • dongposhi8677 dongposhi8677 2015-01-14 00:59

    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.

    点赞 评论 复制链接分享
  • dongsun5330 dongsun5330 2015-01-14 01:02

    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.

    点赞 评论 复制链接分享
  • dongzanghui4624 dongzanghui4624 2015-01-14 01:04

    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]);
        }
    }
    
    点赞 评论 复制链接分享

相关推荐