【问题标题】:Using foreach to print JSON with multidimensional arrays使用 foreach 打印带有多维数组的 JSON
【发布时间】:2018-05-10 03:53:19
【问题描述】:

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

这是一个 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

先谢谢了。

【问题讨论】:

  • 尝试在您的代码中添加var_dump() - 这应该可以让您看到发生了什么。

标签: php json multidimensional-array foreach


【解决方案1】:

使用vardump 代替print

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

我个人更喜欢使用print_r

print_r — 打印关于变量的人类可读信息

【讨论】:

    【解决方案2】:

    你打算这样做吗?

            $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>';
                            }       
                        }
                    }
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 1970-01-01
      • 2012-12-26
      • 2016-01-14
      • 2013-10-27
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多