如何使用json_decode提取内部信息

时间:2012-01-19 13:26:55

标签: php json

我是php的新手。我需要一些json_decode / php的快速帮助。我需要在数组中获取g91的值,我该怎么做?我想有一些递归值可以传递给json_decode ...

{
    "e": "none",
    "f": "test",
    "g": [
        {
            "g1": "text2",
            "g9": {
                "text3": {
                    "g91": 0,
                    "g92": [
                        "text5"
                    ]
                }
            }
        },
        {
            "g1": "text1",          
            "g9": {
                "text4": {
                    "g91": 0,
                    "g92": [
                        "text6",
                        "text7"
                    ]
                }
            }
        }
    ]
}

请注意text3不固定..在下一条记录中,我有text4 ..

谢谢!

4 个答案:

答案 0 :(得分:5)

TRUE传递给json_decode作为第二个参数

$output = json_decode($input,TRUE);

比遍历数组。它应该像

$output['g'][0]['g9']['text3']['g91']

请参阅json_decode

答案 1 :(得分:0)

解码后,您将获得一个PHP数组,只需转到所需的索引:

$myJson['g'][0]['g9']['text3']['g91'];

但是你可以做一些递归循环来找到你在该数组中搜索的所有结果。

查看来自PHP的数组文档:http://br2.php.net/manual/en/book.array.php

答案 2 :(得分:0)

$json = '{
    "e": "none",
    "f": "test",
    "g": [
        {
            "g1": "text2",
            "g9": {
                "text3": {
                    "g91": 0,
                    "g92": [
                        "text5"
                    ]
                }
            }
        },
        {
            "g1": "text1",          
            "g9": {
                "text4": {
                    "g91": 0,
                    "g92": [
                        "text6",
                        "text7"
                    ]
                }
            }
        }
    ]
}';
$result = json_decode($json);
var_dump(array_merge($result->g[0]->g9->text3->g91, $result->g[1]->g9->text3->g91));

答案 3 :(得分:0)

我为测试目的更新了JSON:

<script type="text/javascript">
    var json ={
        "e": "none",
        "f": "test",
        "g": [
            {
                "g1": "text2",
                "g9": {
                    "text3": {
                        "g91": 83,
                        "g92": [
                            "text5"
                        ]
                    }
                }
            },
            {
                "g1": "text1",          
                "g9": {
                    "text4": {
                        "g91": 12,
                        "g92": [
                            "text6",
                            "text7"
                        ]
                    }
                }
            }
        ]
    }
    var arr=json["g"];
    for(key in arr){
       var obj=arr[key]["g9"];
       for(tex in obj)
       {
       alert(obj[tex]["g91"]);
       }
    }
</script>
相关问题