在php中获取json数组中键的值

时间:2014-09-03 09:42:49

标签: php json

如何获取密钥关联的相应值

[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff@gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a@b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]

1 个答案:

答案 0 :(得分:1)

您的Json有效。您可以在以下验证  网站:http://jsonlint.com/

你必须使用php" json_decode()"用于解码json编码数据的函数。 基本上json_decode()函数将JSON数据转换为PHP数组。

语法:json_decode(data,dataTypeBoolean,depth,options)

数据: - 要在PHP中解码的json数据。

dataTypeBoolean(可选): - 布尔值,如果设置为" true",则使函数返回PHP关联数组,如果省略此参数,则返回PHP stdClass对象或设置为" false"。这两种数据类型都可以像数组一样访问,并使用基于数组的PHP循环进行解析。

深度: - 可选的递归限制。使用整数作为此参数的值。

选项: - 可选的JSON_BIGINT_AS_STRING参数。

现在来到您的代码

$json_string = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff@gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a@b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ;

将有效的json数据分配给单个“#”中的变量$ json_string('')as    json字符串已经有双重报价。

// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.

$json_decoded_data = json_decode($json_string, true);

// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);

// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
    echo "$key <br/>";
    foreach ($value as $key2 => $value2) {
        echo "$key2 = $value2 <br />";
    }
}

Output : 
0 
name = challenge 
properties = Array 
1 
name = challenge 
properties = Array 
相关问题