0

我正在尝试遍历通过 jquery/ajax 从 php 文件中检索到的多维关联数组。php 数组如下所示:

$pink =  array ( "newarray" => array 
( "varietyOne" => array
("name" => "Poublout", "year" => 2002),
"varietyTwo" => array
("name" => "Gerarde", "year" => 2003),
"varietyThree" => array
("name" => "Encore", "year" => 1956),
"varietyFour" => array
("name" => "Toujours", "year" => 1957),
"varietyFive" => array
("name" => "J'aime", "year" => 1958),
"varietySix" => array
("name" => "Alisee", "year" => 2001)
),
"varNumber" => array
("varietyOne",
"varietyTwo",
"varietyThree",
"varietyFour",
"varietyFive",
"varietySix"
)
);
print json_encode($pink);

js看起来像这样:

$(document).ready(function () {
    $('.clicker').click(function () {
        $.ajax({
            type: 'GET',
            url: 'another.php',
            dataType: 'json',
            success: function (brandon) {
                for (var i = 0; i < brandon.newarray.length; i++) {
                    var catName = brandon.varNumber[i];
                    for (var wineName in brandon.newarray[i][catName]) {
                        console.log(branond.newarray[i][catName][wineName]);
                    }
                }
            }
        });
    });
});

这是json而不是php:

{"newarray":
    {"varietyOne":{"name":"Poublout","year":2002},
     "varietyTwo":{"name":"Gerarde","year":2003},
     "varietyThree":{"name":"Encore","year":1956},
     "varietyFour":{"name":"Toujours","year":1957},
     "varietyFive":{"name":"J'aime","year":1958},
     "varietySix":{"name":"Alisee","year":2001}},
 "varNumber":
    ["varietyOne","varietyTwo","varietyThree","varietyFour","varietyFive","varietySix"]}

我尝试了几个不同的循环,改变了我的数组值,但我什么都做不了。我可以在数组中调用一个单独的 key=value 对,但我不能让它遍历所有值。
谢谢你。

以及 console.log(brandon) 的结果

Object { newarray={...}, varNumber=[6]}
newarray
Object { varietyOne={...}, varietyTwo={...}, varietyThree={...}, more...}
varietyFive
Object { name="J'aime", year=1958}
varietyFour
Object { name="Toujours", year=1957}
varietyOne
Object { name="Poublout", year=2002}
varietySix
Object { name="Alisee", year=2001}
varietyThree
Object { name="Encore", year=1956}
varietyTwo
Object { name="Gerarde", year=2003}
varNumber
["varietyOne", "varietyTwo", "varietyThree", 3 more...]
0   "varietyOne"
1   "varietyTwo"
2   "varietyThree"
3   "varietyFour"
4   "varietyFive"
5   "varietySix"

因此,循环现在输出到控制台,但我希望文本显示在我的网站上。通常我使用 $('#somediv').append(brandon.(whateverelse); 并且信息会出现。在这种情况下它不会出现。

4

1 回答 1

1

您不需要 varNumber 数组。

所有你需要的是:

for (var index in brandon.newarray) {
    console.log(index);
    console.log(brandon.newarray[index]);
    console.log(brandon.newarray[index]['name']); // or brandon.newarray[index].name
    console.log(brandon.newarray[index]['year']); // or brandon.newarray[index].year
}

在这种情况下,索引将为varietyOne,varietyTwo等。

于 2013-10-14T19:05:32.337 回答