检索动态生成的JSON键和值


Retrieving dynamically generated JSON keys and values

我有下面的JSON结构,我拉入我的PHP脚本作为$_POST请求。活动名称和组名称的键是动态生成的,所以我需要提取这些键,这样我就可以组每个活动与它的组名和广告副本到单独的数组。

我在这里看到了几个非常相似的帖子,但到目前为止,这些解决方案都没有奏效。我觉得我把这事弄得太复杂了。

{
    "First Campaign Name": {
        "First Group Name": {
            "textads": [
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ],
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ]
            ]
        },
        "Second Group Name": {
            "textads": [
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ],
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ]
            ]
        }
    },
    "Second Campaign Name": {
        "First Group Name": {
            "textads": [
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ],
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ]
            ]
        },
        "Second Group Name": {
            "textads": [
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ],
                [
                    "{Headline text}",
                    "First line text",
                    "Second line text",
                    "Display URL"
                ]
            ]
        }
    }
}

我已经尝试了几个foreach和嵌套foreach循环试图访问键和值没有运气。我最近的尝试是:

foreach($jsonString as $campaign) {
    foreach($campaign as $k => $v){
        $postData .= "Key: " . $k . "'r'n";
        $postData .= "Val: " . $v . "'r'n";
    }
}

其中$postData已经定义,然后保存到文件中用于输出。我还尝试了以下操作:

foreach ($_POST as $key => $value) {
    foreach( $value as $item){
        foreach( $item as $k => $v){
           $postData .= "Key: " . $k . "'r'n";
           $postData .= "Val: " . $v . "'r'n";
        }
    }
}

您需要将JSON转换为php数组,然后才能与foreach一起使用。

$phparray = json_decode ($jsonString);

http://php.net/manual/en/function.json-decode.php