我怎么能在php中计算不同的值关联数组

时间:2011-03-23 13:48:02

标签: php facebook

我有F8喜欢json文件,我想存储和计算数组中的类别,即php中的简单数组

function array_icount_values($array) {
   $rtarray = array();
    foreach($array as $value) $rtarray[strtolower($value)]++;
    return $rtarray; 
$ar = array('red', 'green', 'blue', 'red', 'red', 'red', 'blue', 'blue', 'green');
//$ar = array_icount_values($re);

其输出将是

[red]=>4
[blue]=>3
[green]=>2

我希望此文件的结果相同

{
   "data": [
      {
         "name": "The Lord of the Rings Trilogy (Official Page)",
         "category": "Movie"         
      },
      {
         "name": "Snatch",
         "category": "Movie"

      },
      {         "name": "The Social Network Movie",
         "category": "Movie"         
      },
      {         "name": "Scarface",
         "category": "public figure"         
      },
      {         "name": "Johnny Depp",
         "category": "Actor/director"         
      },
      {
         "name": "Once Upon a Time in the West",
         "category": "public figure"         
      },
      {         "name": "Legend of the Guardians: The Owls of Ga'Hoole",
         "category": "public figure"         
      },
      {         "name": "Once Upon a Time in America",
         "category": "public figure"       
      },
      {         "name": "Butch Cassidy and the Sundance Kid",
         "category": "public figure"
        },
      {         "name": "Fracture",
         "category": "public figure"
              },
      {         "name": "Invictus",
         "category": "public figure"

      },
      { "name": "Pride and Glory",
         "category": "public figure"
      }
   ]
}

注意我只想要类别计数,即

[Movies]=>5 [Tv show]=>4 etc
我使用了这段代码
function array_icount_values($array) {
    $ret_ar=array();
    foreach($array['data'] as $key=>$val)
    {
        print_r(array_count_values($val));
     }}
$string = file_get_contents("likes.json");
$json_a=json_decode($string,true);
$re=array_icount_values($json_a);
但这会产生奇怪的结果。

1 个答案:

答案 0 :(得分:1)

你在那里的文字是一个JSON。只需使用与之前提供的函数相同的方法对其进行解码即可对其进行解码。看看这个:http://www.php.net/manual/en/function.json-decode.php

希望我能帮助你,一切顺利......

LE

$arr=json_decode($str);
foreach($arr['data'] as $value){
    $categCount[$value['category']]++;
}

var_dump($ categCount); //应该为您提供类别计数