使用foreach打印具有多维数组的JSON

时间:2017-11-26 23:04:03

标签: php json multidimensional-array foreach

您好我正在使用Bing网络搜索API,并需要一些帮助,使用PHP将JSON转换为html。所以我想能够使用foreach()和if()语句打印选择性员工。我已经看过其他的主题,但我无法弄清楚这是什么问题。

这是一个JSON示例:

{
"_type": "SearchResponse",
"queryContext": {
    "originalQuery": "Microsoft Cognitive Services"
},
"webPages": {
    "webSearchUrl": "https:\/\/www.bing.com\/search?q=Microsoft+Cognitive+Services",
    "totalEstimatedMatches": 2320000,
    "value": [
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.0",
            "name": "Cognitive Services | Microsoft Azure",
            "url": "https:\/\/azure.microsoft.com\/es-es\/services\/cognitive-services\/",
            "displayUrl": "https:\/\/azure.microsoft.com\/es-es\/services\/cognitive-services",
            "snippet": "Agregue funcionalidades de visi\u00f3n, voz, lenguaje y conocimiento a sus aplicaciones mediante las API de inteligencia artificial de Cognitive Services.",
            "dateLastCrawled": "2017-11-22T05:45:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.1",
            "name": "Microsoft Cognitive Services: Componentes del Servicio ...",
            "url": "https:\/\/azure.microsoft.com\/es-es\/support\/legal\/cognitive-services-components\/",
            "displayUrl": "https:\/\/azure.microsoft.com\/es-es\/support\/legal\/cognitive-services...",
            "snippet": "Revise el uso de los t\u00e9rminos de Microsoft Cognitive Services: Componentes del Servicio.",
            "dateLastCrawled": "2017-11-21T02:34:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.2",
            "name": "Microsoft Trust Center | Microsoft Cognitive Services",
            "url": "https:\/\/www.microsoft.com\/en-us\/trustcenter\/cloudservices\/cognitiveservices",
            "displayUrl": "https:\/\/www.microsoft.com\/...\/cloudservices\/cognitiveservices",
            "snippet": "Microsoft Cognitive Services is a collection of intelligent APIs that allow systems to understand and interpret people\u2019s needs by using natural methods ...",
            "dateLastCrawled": "2017-11-18T16:46:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.3",
            "name": "Cognitive Services | Microsoft Azure",
            "url": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services\/",
            "displayUrl": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services",
            "snippet": "Add vision, speech, language and knowledge capabilities to your apps with artificial intelligence APIs from Cognitive Services. Explore our APIs today.",
            "dateLastCrawled": "2017-11-22T02:20:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.4",
            "name": "Cognitive Service Try experience | Microsoft Azure",
            "url": "https:\/\/azure.microsoft.com\/en-us\/try\/cognitive-services\/",
            "displayUrl": "https:\/\/azure.microsoft.com\/en-us\/try\/cognitive-services",
            "snippet": "Microsoft Cognitive Services Try experience lets you build apps with powerful algorithms using just a few lines of code through a 30 day trial.",
            "dateLastCrawled": "2017-11-21T02:42:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.5",
            "name": "Cognitive Services Directory | Microsoft Azure",
            "url": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services\/directory\/",
            "displayUrl": "https:\/\/azure.microsoft.com\/...\/services\/cognitive-services\/directory",
            "snippet": "Learn more about Cognitive Services and manage them in the Azure cloud, or test them with temporary access.",
            "dateLastCrawled": "2017-11-21T21:14:00.0000000Z"
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.6",
            "name": "What is Microsoft Cognitive Services? | Microsoft Docs",
            "url": "https:\/\/docs.microsoft.com\/en-us\/azure\/cognitive-services\/Welcome",
            "displayUrl": "https:\/\/docs.microsoft.com\/en-us\/azure\/cognitive-services\/Welcome",
            "snippet": "Microsoft Cognitive Services is a set of APIs, SDKs, and services that you can use with Microsoft Azure that make applications more intelligent, engaging ...",
            "dateLastCrawled": "2017-11-21T17:40:00.0000000Z",
            "searchTags": [
                {
                    "name": "search.ms_sitename",
                    "content": "\"Docs\"; docs"
                },
                {
                    "name": "search.ms_docsetname",
                    "content": "\"azure-documents\"; azure; documents"
                },
                {
                    "name": "search.ms_product",
                    "content": "\"Azure\"; azure"
                }
            ]
        },
        {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.7",
            "name": "Microsoft Cognitive Services",
            "url": "https:\/\/westus.dev.cognitive.microsoft.com\/docs\/services\/TextAnalytics.V2.0\/operations\/56f30ceeeda5650db055a3c7",
            "displayUrl": "https:\/\/westus.dev.cognitive.microsoft.com\/docs\/services\/Text...",
            "snippet": "Text Analytics API. The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms.",
            "dateLastCrawled": "2017-11-22T13:25:00.0000000Z"
        }
    ]
}

我想打印一些内容" webPages",我使用以下php代码:

$links = json_decode($json, TRUE);

foreach ($links['webPages'] as $j => $v) {
    if($j=="value"){
        foreach ($v as $k => $w) {
            print $k . ": " . $w;
        }
    }

}

我收到以下错误:

Notice: Array to string conversion

它打印出来:

0: Array
1: Array
...
7: Array

事先谢谢。

2 个答案:

答案 0 :(得分:0)

使用print

vardump个实例
  

var_dump - 此函数显示有关包含其类型和值的一个或多个表达式的结构化信息

我个人更喜欢使用print_r

  

print_r - 打印有关变量的可读信息

答案 1 :(得分:0)

你打算这个?

        $json  = '{
        "_type": "SearchResponse",
        "queryContext": {
            "originalQuery": "Microsoft Cognitive Services"
        },
        "webPages": {
            "webSearchUrl": "https:\/\/www.bing.com\/search?q=Microsoft+Cognitive+Services",
            "totalEstimatedMatches": 2320000,
            "value": [
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.0",
                    "name": "Cognitive Services | Microsoft Azure",
                    "url": "https:\/\/azure.microsoft.com\/es-es\/services\/cognitive-services\/",
                    "displayUrl": "https:\/\/azure.microsoft.com\/es-es\/services\/cognitive-services",
                    "snippet": "Agregue funcionalidades de visi\u00f3n, voz, lenguaje y conocimiento a sus aplicaciones mediante las API de inteligencia artificial de Cognitive Services.",
                    "dateLastCrawled": "2017-11-22T05:45:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.1",
                    "name": "Microsoft Cognitive Services: Componentes del Servicio ...",
                    "url": "https:\/\/azure.microsoft.com\/es-es\/support\/legal\/cognitive-services-components\/",
                    "displayUrl": "https:\/\/azure.microsoft.com\/es-es\/support\/legal\/cognitive-services...",
                    "snippet": "Revise el uso de los t\u00e9rminos de Microsoft Cognitive Services: Componentes del Servicio.",
                    "dateLastCrawled": "2017-11-21T02:34:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.2",
                    "name": "Microsoft Trust Center | Microsoft Cognitive Services",
                    "url": "https:\/\/www.microsoft.com\/en-us\/trustcenter\/cloudservices\/cognitiveservices",
                    "displayUrl": "https:\/\/www.microsoft.com\/...\/cloudservices\/cognitiveservices",
                    "snippet": "Microsoft Cognitive Services is a collection of intelligent APIs that allow systems to understand and interpret people\u2019s needs by using natural methods ...",
                    "dateLastCrawled": "2017-11-18T16:46:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.3",
                    "name": "Cognitive Services | Microsoft Azure",
                    "url": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services\/",
                    "displayUrl": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services",
                    "snippet": "Add vision, speech, language and knowledge capabilities to your apps with artificial intelligence APIs from Cognitive Services. Explore our APIs today.",
                    "dateLastCrawled": "2017-11-22T02:20:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.4",
                    "name": "Cognitive Service Try experience | Microsoft Azure",
                    "url": "https:\/\/azure.microsoft.com\/en-us\/try\/cognitive-services\/",
                    "displayUrl": "https:\/\/azure.microsoft.com\/en-us\/try\/cognitive-services",
                    "snippet": "Microsoft Cognitive Services Try experience lets you build apps with powerful algorithms using just a few lines of code through a 30 day trial.",
                    "dateLastCrawled": "2017-11-21T02:42:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.5",
                    "name": "Cognitive Services Directory | Microsoft Azure",
                    "url": "https:\/\/azure.microsoft.com\/en-us\/services\/cognitive-services\/directory\/",
                    "displayUrl": "https:\/\/azure.microsoft.com\/...\/services\/cognitive-services\/directory",
                    "snippet": "Learn more about Cognitive Services and manage them in the Azure cloud, or test them with temporary access.",
                    "dateLastCrawled": "2017-11-21T21:14:00.0000000Z"
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.6",
                    "name": "What is Microsoft Cognitive Services? | Microsoft Docs",
                    "url": "https:\/\/docs.microsoft.com\/en-us\/azure\/cognitive-services\/Welcome",
                    "displayUrl": "https:\/\/docs.microsoft.com\/en-us\/azure\/cognitive-services\/Welcome",
                    "snippet": "Microsoft Cognitive Services is a set of APIs, SDKs, and services that you can use with Microsoft Azure that make applications more intelligent, engaging ...",
                    "dateLastCrawled": "2017-11-21T17:40:00.0000000Z",
                    "searchTags": [
                        {
                            "name": "search.ms_sitename",
                            "content": "\"Docs\"; docs"
                        },
                        {
                            "name": "search.ms_docsetname",
                            "content": "\"azure-documents\"; azure; documents"
                        },
                        {
                            "name": "search.ms_product",
                            "content": "\"Azure\"; azure"
                        }
                    ]
                },
                {
                    "id": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.7",
                    "name": "Microsoft Cognitive Services",
                    "url": "https:\/\/westus.dev.cognitive.microsoft.com\/docs\/services\/TextAnalytics.V2.0\/operations\/56f30ceeeda5650db055a3c7",
                    "displayUrl": "https:\/\/westus.dev.cognitive.microsoft.com\/docs\/services\/Text...",
                    "snippet": "Text Analytics API. The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms.",
                    "dateLastCrawled": "2017-11-22T13:25:00.0000000Z"
                }
            ]
        }}';

        $links = json_decode($json);
        $links = objectToArray($links);

        foreach ($links as $j=>$v) {
            //print $j.'<br>';
            if($j == "webPages"){
                foreach ($v as $k) {
                    if (is_array($k)){
                        foreach ($k as $i=>$t){
                            if (is_array($t)){
                                foreach ($t as $l=>$m){
                                    print "<b> $l </b>" .' : ' .$m.'<br>';
                                }   
                            }
                        }
                    }
                }
            }
        }

function objectToArray($stdClass) {

if (is_object($stdClass)) {
    //recupera le proprietà dell'oggetto
    $stdClass = get_object_vars($stdClass);
}
if (is_array($stdClass)) {
    //ritorna l'array convertito in oggetto per chiamata ricorsiva
    return array_map(__FUNCTION__, $stdClass);
}
else {
    //ritorna l'array
    return $stdClass;
}
}

同样以这种方式有一个foreach in less:)

        $links = json_decode($json);
        $links = objectToArray($links);
        foreach ($links['webPages'] as $j => $v) {
            if(is_array($v)){
                foreach ($v as $k => $w) {
                    if (is_array($w)){
                        foreach($w as $t=>$l){
                            print '<b>'.$t."</b> : ".$l.'<br>';
                        }       
                    }
                }
            }
        }