2011-03-23 58 views
0

我有F8等JSON文件,我想存儲和在PHP即,對於簡單的數組的數組計數的類別如何可以計數不同的值在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);
但這給了奇怪的結果。

+0

解碼json +'foreach($ array as $ value)$ rtarray [strtolower($ value ['category'])] ++;' – biakaveron 2011-03-23 13:55:22

+0

看我更新的問題 – hunter 2011-03-23 13:59:09

回答

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); //應該給你的類別數

+0

我解碼json文件並應用該方法,但沒有得到我的結果 – hunter 2011-03-23 13:57:07

+0

應用該方法(作爲ideea),而不是函數:)。解碼之後,你應該得到一個數組像$ array ['data'],我會在一秒內給你上面的其餘部分 – Catalin 2011-03-23 14:17:38

+1

使用$ value ['category']作爲索引給出了一個「未定義索引」異常,什麼是正確的方法解決這個問題? :) – Dane411 2015-08-18 18:53:55