开发者

how to parse this json in php

hello all i have a json file i.e

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

i want to parse this file in php and get the value of all categories my php code is

<?php
error_reporting(E_ALL);开发者_如何学Go
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'];
}?>

but i get this error

Notice: Undefined index: category in /var/www/json app/test.php on line 7

also how can i get the mode(The mode is the number that is repeated more often than any other) of category in this file i.e in this example "Movie" is the mode of the list.


var_dump($json_a);

Right after json_decode and you'll see that array is nested into data, so

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜