简体   繁体   English

从json动态选择元素

[英]Select element from json dynamically

I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var 我在php中有一个关联数组,我解析以从中获取json(json_encode),然后将结果存储在javascript var中

var myArray = <?php print json_encode($phpArray); ?>;

Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element : 现在,当用户按下按钮时,我应该动态地从数组中选择另一个元素,例如,我选择了一个随机的第一个元素:

var an_element = myArray.a2.link;

-'a2' is an array in the main array -'a2'是主数组中的一个数组

-'link' is an element in the a2 array. -“链接”是a2数组中的元素。

So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.) I tried this : 所以现在当用户按下我的按钮时,我想选择一个随机的其他数组ID(例如a5,a9等),我尝试了以下操作:

var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;

It doesn't works, it says myArray.newRandomArrayID is undefined. 它说myArray.newRandomArrayID是未定义的,这是行不通的。 Anyone can help? 有人可以帮忙吗? Thank you 谢谢

You need to use [] indexing to find properties by name: 您需要使用[]索引来按名称查找属性:

an_element = myArray[newRandomArrayID].link;

Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property. 否则,JS会在myArray上查找实际上称为newRandomArrayID的属性,而不是使用变量的值来查找该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM