简体   繁体   中英

how can i count distinct values associative array in php

i have F8 like json file and i want to store and count the categories in an array ie for simple array in 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);

its output will be

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

i want same result for this file

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

that i just want the categories count ie ,我只希望类别计数,即

[Movies]=>5 [Tv show]=>4 etc
i used this code
 function array_icount_values($array) { \n    $ret_ar=array(); \n    foreach($array['data'] as $key=>$val) \n    { \n        print_r(array_count_values($val)); \n     }} \n$string = file_get_contents("likes.json"); \n$json_a=json_decode($string,true); \n$re=array_icount_values($json_a);  
But this give strange result.

The text you have there is a JSON. Just decode it an use the same method to count categories as in the function you previously provided. Check this out: http://www.php.net/manual/en/function.json-decode.php

Hope I could help, all the best...

LE:

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

var_dump($categCount);// should give you the categories count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM