【问题标题】:PHP - JSON Data Parsing [duplicate]PHP - JSON 数据解析 [重复]
【发布时间】:2010-01-14 21:04:23
【问题描述】:

全部,

我有以下 JSON 数据。我需要帮助在 PHP 中编写一个函数,该函数接受一个 categoryid 并在一个数组中返回属于它的所有 URL。

类似这样的::

<?php
function returnCategoryURLs(catId)
{
    //Parse the JSON data here..
    return URLArray;
}
?>


{
    "jsondata": [
        {
            "categoryid": [
                20 
            ],
            "url": "www.google.com" 
        },
        {
            "categoryid": [
                20 
            ],
            "url": "www.yahoo.com" 
        },
        {
            "categoryid": [
                30 
            ],
            "url": "www.cnn.com" 
        },
        {
            "categoryid": [
                30 
            ],
            "url": "www.time.com" 
        },
        {
            "categoryid": [
                5,
                6,
                30 
            ],
            "url": "www.microsoft.com" 
        },
        {
            "categoryid": [
                30 
            ],
            "url": "www.freshmeat.com" 
        } 
    ]
}

谢谢

【问题讨论】:

    标签: php json


    【解决方案1】:

    这样的事情怎么样:


    你首先使用json_decode,这是php的内置函数来解码JSON数据:

    $json = '{
        ...
    }';
    $data = json_decode($json);
    

    在这里,您可以看到 PHP 类型的数据(即对象、数组、...) JSON 字符串的解码给您提供了哪些数据,例如:

    var_dump($data);
    


    然后,您遍历数据项,在每个元素的 categoryid 中搜索,如果您正在搜索的 $catId 在列表中 - in_array 有助于这样做:

    $catId = 30;
    $urls = array();
    foreach ($data->jsondata as $d) {
        if (in_array($catId, $d->categoryid)) {
            $urls[] = $d->url;
        }
    }
    

    并且,每次找到匹配项时,将 url 添加到数组中...


    这意味着,在循环结束时,您将获得 URL 列表:

    var_dump($urls);
    

    在这个例子中给你:

    array
      0 => string 'www.cnn.com' (length=11)
      1 => string 'www.time.com' (length=12)
      2 => string 'www.microsoft.com' (length=17)
      3 => string 'www.freshmeat.com' (length=17)
    


    由你来构建 - 应该没有太多工作要做;-)

    【讨论】:

      【解决方案2】:

      试试内置的json_decode函数。

      【讨论】:

        猜你喜欢
        • 2017-09-01
        • 2020-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多