簡體   English   中英

從javascript訪問屬性多維數組PHP

[英]Accessing properties multimendional array PHP from javascript

我在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);
        ?>

我正在嘗試從javascript到javascript的此數組的屬性訪問,但尚未到達。

我試過了

<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>

我可以訪問年份 ,但不能訪問其他屬性。

打印以下內容:

2001:
[object Object]
[object Object]
2002:
[object Object]
[object Object]

由於每個月都是一個數組-您不需要額外的循環來獲取該月份數組中的值。 其結果將是:

$('#year').append(data[i].month[x][0] //= val1 within month[x]
$('#year').append(data[i].month[x][1] //= val2 within month[x]

因此您將需要三個嵌套循環:

//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];

解碼使用PHP json_encode創建的JSON后,將在Javascript對象中轉換非數字數組。 如果需要數組,請嘗試使用數字關鍵字。

某些瀏覽器(例如chrome)會按字母順序對對象的關鍵字排序。 如果您想迭代對象,則需要先知道這一點。

一個建議:使用$ .each i jQuery迭代數組或對象更為簡單。

$.each(data, function(key, value){
...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM