簡體   English   中英

如何在php中解析這個json

[英]how to parse this json in php

你好,我有一個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

另外,我如何獲得該文件中的類別模式(模式是比任何其他模式更頻繁重復的數字),即在此示例中,“電影”是列表的模式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM