PHP - JSON Veri Ayrıştırma

2 Cevap php

Tümü,

Ben şu JSON Veri var. Ben bir CategoryID alır ve bir dizide kendisine ait tüm URL'leri döndüren PHP bir işlevi yazma yardıma ihtiyacım var.

Böyle bir şey ::

<?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" 
        } 
    ]
}

Teşekkürler

2 Cevap

Ne bu böyle bir şey:


You first use json_decode, which is php's built-in function to decode JSON data :

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

Burada, (i.e. objects, arrays, ...) JSON dize çözme, örneğin kullanarak, size ne verdi PHP tür veri görülebilmektedir:

var_dump($data);


And, then, you loop over the data items, searching in each element's categoryid if the $catId you are searching for is in the list -- in_array helps doing that :

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

Ve, bir eşleşme bulmak her zaman, bir dizi url ekleyin ...


Which means that, at the end of the loop, you have the list of URLs :

var_dump($urls);

Bu örnekte, size verir:

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)


Up to you to build from this -- there shouldn't be much left to do ;-)

Yerleşik json_decode fonksiyonu deneyin.