PHP-JSON数据解析
全部, 我有以下JSON数据。我需要帮助在PHP中编写一个函数,它接受categoryid并在数组中返回属于它的所有URL 大概是这样的::PHP-JSON数据解析,php,json,Php,Json,全部, 我有以下JSON数据。我需要帮助在PHP中编写一个函数,它接受categoryid并在数组中返回属于它的所有URL 大概是这样的:: <?php function returnCategoryURLs(catId) { //Parse the JSON data here.. return URLArray; } ?> { "jsondata": [ { "categoryid": [
<?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"
}
]
}
{
“jsondata”:[
{
“类别ID”:[
20
],
“url”:“www.google.com”
},
{
“类别ID”:[
20
],
“url”:“www.yahoo.com”
},
{
“类别ID”:[
30
],
“url”:“www.cnn.com”
},
{
“类别ID”:[
30
],
“url”:“www.time.com”
},
{
“类别ID”:[
5.
6.
30
],
“url”:“www.microsoft.com”
},
{
“类别ID”:[
30
],
“url”:“www.freshmeat.com”
}
]
}
谢谢试试内置功能。这样的功能怎么样:
首先使用php的内置函数来解码JSON数据:
$json = '{
...
}';
$data = json_decode($json);
在这里,您可以看到JSON字符串的解码为您提供了什么样的PHP数据(即对象、数组等),例如:
var_dump($data);
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)
然后,在数据项上循环,如果要搜索的
$catId
在列表中,则搜索每个元素的类别ID
,这有助于:
$catId = 30;
$urls = array();
foreach ($data->jsondata as $d) {
if (in_array($catId, $d->categoryid)) {
$urls[] = $d->url;
}
}
并且,每次找到匹配项时,将url
添加到数组中
这意味着,在循环结束时,您有URL列表:
var_dump($urls);
在本例中,为您提供:
var_dump($data);
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)
由您自己来构建--应该没有多少事情要做;-)