循环遍历以JSON编码的PHP数组 [英] Loop Through PHP Array Encoded In JSON

查看:188
本文介绍了循环遍历以JSON编码的PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP数组,其表ID为键,表字段为值.

I have a PHP array that has a table id as the key and a table field as the value.

PHP示例:

while($row = mysql_fetch_array($result))
{
    $id = $row['id'];
    $array[$id] = $row['some_field'];
}

然后我使用json_encode($array)得到类似的东西:

I then use json_encode($array) to get something like:

{"id1":"value1","abc":"123","xyz":"789"}

如何在jQuery中循环浏览?从到目前为止的发现来看,我似乎需要知道密钥.所以:

How can I loop through this in jQuery? From what I have found so far it seems like I need to know the key. So:

var obj = jQuery.parseJSON(jsonVar);
alert(obj.abc); //prints 123

但是如果我不知道这些键是动态的,那么如何获得这些值呢?
我需要重组我的PHP数组吗?

But how can I get these values if I don't know the keys since they are dynamic?
Do I need to restructure my PHP array?

推荐答案

在php中将关联数组编码为JSON对象后,它不再是数组,而是具有键和值的对象.您可以使用 for..in在javascript中对其进行遍历.

Once you encode an associative array in php into a JSON object it is no longer an array, it is an object with keys and values. You can iterate through them in javascript using for..in

for (var key in obj) {
   console.log(obj[key]);
}

注意:for..in不保留顺序,如果需要确保顺序,则必须使数组索引而不是key=>value,并使用for循环(或while).

Note: for..in does not garuntee order, if you need to ensure order you will have to make your array indexed, instead of key=>value, and use a for loop (or while) instead.

这篇关于循环遍历以JSON编码的PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆