Php 从jquery对象获取特定键和值
我正在从php关联数组到jquery对象获取键和值:Php 从jquery对象获取特定键和值,php,jquery,Php,Jquery,我正在从php关联数组到jquery对象获取键和值: $names = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); $js = json_encode($names); echo 'var names= ' . $js . ";"; 现在我知道了如何遍历所有名称并获取它们的键和值: $.each(names, function(key, value){ alert(key + value); }); 但我只需要特定的
$names = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$js = json_encode($names);
echo 'var names= ' . $js . ";";
现在我知道了如何遍历所有名称并获取它们的键和值:
$.each(names, function(key, value){
alert(key + value);
});
但我只需要特定的值。例如,如何只获取“Ben”和“37”而不遍历所有名称?您可以使用
对象键来实现这一点
var index = 1; // the nth key you want to fetch, 1 will be second
key = Object.keys(names)[index];
value = names[key];
console.log(key + ' -> ' + value);
将输出
Ben -> 37
您可以使用Object.keys
var index = 1; // the nth key you want to fetch, 1 will be second
key = Object.keys(names)[index];
value = names[key];
console.log(key + ' -> ' + value);
将输出
Ben -> 37
console.log(names.Ben)代码>?但我不知道钥匙。我不知道名字叫本。我想获取键和值,尝试添加新数组(),如:echo'var names=new Array('.$js.);“@matip如果你不知道钥匙,那么你怎么知道你要取回什么?你知道值吗?我想得到第二个键和值。这可能吗?console.log(names.Ben)代码>?但我不知道钥匙。我不知道名字叫本。我想获取键和值,尝试添加新数组(),如:echo'var names=new Array('.$js.);“@matip如果你不知道钥匙,那么你怎么知道你要取回什么?你知道值吗?我想得到第二个键和值。可能吗?