WXR
WXR

Reputation: 591

How to use php to count the same array?

I read a few of the threads but none of them seem to match what I need. What I'm trying to do it something like a voting system but does not include mysql at the moment.

I made three radio buttons of music types pop, rock, metallic and a submit so whichever a person choose either one of them and submit the data is wrote into a data.json and stored there.

Then I have a page to load all the data in data.json file but I want to count how many people selected for example metallic and how many people selected rock.

At the moment I'm still testing and I actually thought of an idea but somehow searched up and not getting what I want.....can someone give me a hand?

This is my data.json file

{"type":"metallic"}
{"type":"pop"}
{"type":"metallic"}

and this is what my result code is at the moment

<?php
$file = fopen('data.json', "r");       

$array_record = array();

while(!feof($file))                       
{
    $line = fgets($file);                 
    $data = json_decode($line, TRUE);     

    if (is_array($data))                  
    {                
        foreach ($data as $key => $value) 
        {
           // echo $key.'='.$value.' ';      // show key=value pairs
          $array_record += array($value,);
          var_dump($data);
          print_r($data);
          echo $value;

        }
        echo '<br>'.PHP_EOL;             
    }
}


fclose($file);                          
?>

I know the codes are messy because I tried setting up an empty array first then get the $value which is something like metallic into an array so I can use the array_count_values but the way I'm doing it seems totally wrong or that'd never work. I tried few other ways to get only metallic/pop so I can try counting the same thing.

AH! I just found this topic How to filter JSON array into PHP array

I'm going to read this thread tomorrow and see if it helps. But it wouldn't hurt if you can give me a hand too.

Upvotes: 0

Views: 157

Answers (1)

Prix
Prix

Reputation: 19528

Keep in mind the JSON you have posted is a not a valid JSON.

array_reduce:

<?php
$json = '[{"type":"metallic"},{"type":"pop"},{"type":"metallic"}]';
$result = array_reduce(json_decode($json,TRUE),
    function($v, $item)
    {
        if (!array_key_exists($item['type'], $v))
            $v[$item['type']] = 1;
        else
            $v[$item['type']]++;
        return $v;
    }, array()
);
print_r($result);

Live DEMO.

Upvotes: 1

Related Questions