你好,我有一个json文件,即
{
"data": [
{
"name": "The Lord of the Rings Trilogy (Official Page)",
"category": "Movie"
},
{
"name": "Snatch",
"category": "Drama"
},
{
"name": "The Social Network Movie",
"category": "Movie"
},
{
"name": "Scarface\u2122",
"category": "Movie"
}
]
}
我想在php中解析这个文件并获取我的php代码所有类别的值
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
$string = file_get_contents("test.json");
$json_a=json_decode($string,true);
foreach ($json_a as $category_name => $category) {
echo $category['category'];
}?>
但我收到此错误
Notice: Undefined index: category in /var/www/json app/test.php on line 7
该怎样才能获得该文件中的类别模式(模式是比任何其他模式更频繁重复的数字),即在此示例中“电影”是列表的模式。
答案 0 :(得分:2)
var_dump($json_a);
在json_decode
之后,您会看到该数组嵌套在data
中,所以
foreach ($json_a['data'] as $category_name => $category) {
echo $category['category'];
}
<强> UPD 强>
$string = '{
"data": [
{
"name": "The Lord of the Rings Trilogy (Official Page)",
"category": "Drama"
},
{
"name": "Snatch",
"category": "Movie"
},
{
"name": "The Social Network Movie",
"category": "Movie"
},
{
"name": "Scarface\u2122",
"category": "Movie"
}
]
}';
$json_a=json_decode($string,true);
$categories = array();
foreach ($json_a['data'] as $category_name => $category) {
$categories[] = $category['category'];
}
$categories_cnt = array_count_values($categories);
arsort($categories_cnt);
$categories_titles = array_keys($categories_cnt);
$most_frequent_word = reset($categories_titles);
var_dump($most_frequent_word);