问题描述
全部
我有以下JSON数据.我需要用PHP编写一个函数,该函数接受一个categoryid并以数组形式返回属于它的所有URL.
I have the following JSON Data. I need help writing a function in PHP which takes a categoryid and returns all URLs belonging to it in an array.
类似这样的东西:
<?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"
}
]
}
谢谢
推荐答案
这样的事情怎么样:
您首先使用 json_decode
,这是php的内置功能,可解码JSON数据:
You first use json_decode
, which is php's built-in function to decode JSON data :
$json = '{
...
}';
$data = json_decode($json);
在这里,您可以看到什么样的PHP数据(即对象,数组等) JSON字符串的解码为您提供了例如,
Here, you can seen what PHP kind of data (i.e. objects, arrays, ...) the decoding of the JSON string gave you, using, for example :
var_dump($data);
然后,您遍历数据项,如果要搜索的$catId
在列表中,则在每个元素的categoryid
中搜索- in_array
可以帮助您做到这一点:
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;
}
}
而且,每次找到匹配项时,将url
添加到数组中...
And, each time you find a match, add the url
to an array...
这意味着,在循环结束时,您将获得URL列表:
Which means that, at the end of the loop, you have the list of URLs :
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)
由您决定要从中构建-剩下的工作不多;-)
Up to you to build from this -- there shouldn't be much left to do ;-)
这篇关于PHP-JSON数据解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!