Php 如何从嵌套的JSON数据中获取值?
以下是我的JSON代码:Php 如何从嵌套的JSON数据中获取值?,php,json,Php,Json,以下是我的JSON代码: { "query": { "count": 2, "created": "2013-04-03T09:47:03Z", "lang": "en-US", "results": { "yctCategories": { "yctCategory": { "score": "0.504762",
{
"query": {
"count": 2,
"created": "2013-04-03T09:47:03Z",
"lang": "en-US",
"results": {
"yctCategories": {
"yctCategory": {
"score": "0.504762",
"content": "Computing"
}
},
"entities": {
"entity": [
{
"score": "0.902",
"text": {
"end": "19",
"endchar": "19",
"start": "0",
"startchar": "0",
"content": "Computer programming"
},
"wiki_url": "http://en.wikipedia.com/wiki/Computer_programming"
},
{
"score": "0.575",
"text": {
"end": "51",
"endchar": "51",
"start": "41",
"startchar": "41",
"content": "programming"
}
}
]
}
}
}
}
下面是我的PHP代码
$json_o = json_decode($json,true);
echo "Json result:</br>";
echo $json; // json
echo "</br></br>";
echo "Value result:</br>";
$result = array();
//$entity = $json_o['query']['results']['entities']['entity'];
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
foreach ($theentity['text'] as $thetext){
$result[] = $thetext['content'];
}
print_r($result);
删除第二个foreach并将其替换为
$result[]=$theentity['text']['content']代码>
使用类似的东西可能会使您更容易了解json的结构。或者,只需var\u dump
(或print\r
)json解码的输出使用此循环
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
{
$result[] = $theentity['text']['content'];
}
输出数组([0]=>计算机编程[1]=>编程)使用简单代码:
$array = $json_o['query']['results']['entities']['entity'];
foreach($array as $v){
echo $v['text']['content'];
}
将您的foreach更改为:
$result = array();
foreach ($json_o['query']['results']['entities']['entity'] as $theentity) {
$result[] = $theentity['text']['content'];
}
print_r($result);
$theentity['text']
是一个键数组=>值。您只需访问keycontent
,而无需遍历所有条目
另一种方法是(尽管这是一个糟糕的选择):
我提供第二个示例来说明为什么原始代码不起作用
更新
要访问其他属性,如yctCategories
,只需执行类似操作
$categories = array();
foreach ($json_o['query']['results']['yctCategories'] as $yctCategory) {
$categories[] = $yctCategory['content'];
}
print_r($categories);
不必要地复制数据,没有理由在这里效率低下。@Rickburges ok,但提供了更高的可读性:)和性能editing@Akam谢谢澄清。。它给了我写代码的其他选择
foreach($theentity['text'] as $key => $value) {
if( 'content' === $key ) {
$result[] = $value;
}
}
$categories = array();
foreach ($json_o['query']['results']['yctCategories'] as $yctCategory) {
$categories[] = $yctCategory['content'];
}
print_r($categories);