Jump to content

how to count same data in json from php?


et4891
Go to solution Solved by Ch0cu3r,

Recommended Posts

Sorry I think my topic question is weird but just want to make the wordings as less as possible.

 

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.

Thanks in advance.

Edited by et4891
Link to comment
Share on other sites

There's really no sense in storing every single vote like that. Wouldn't it be a lot easier if you stored the type and the number of votes? Can even be an object like

{"metallic":2,"pop":1}
Oh, and you really should be using a database for this, because otherwise you need to learn about file locking to prevent votes from being lost if they happen simultaneously.
Link to comment
Share on other sites

Normally I'd advice very strongly to log each vote separately. not only because you can get much more interesing data from it, but also because you can record who has voted and prevent them fro voting more than once.

 

But, if that doesn't matter then I'd second requinix: count only the totals.

 

To answer the question itself:

What does your JSON really look like? I dont think it's just what you posted because that's not valid json.

Link to comment
Share on other sites

Darn, I missed that. I seem to be missing alot the last couple of days.

 

Well in that case just grab the value of the 'type' field and use it as an index in the count array:

 

$counts = array('foo'=>0,'bar'=>0,'wibble'=>0);

 

// loop

$count[$value_from_json]  += 1;

 

and at the end:

var_dump($count);

Link to comment
Share on other sites

There's really no sense in storing every single vote like that. Wouldn't it be a lot easier if you stored the type and the number of votes? Can even be an object like

{"metallic":2,"pop":1}
Oh, and you really should be using a database for this, because otherwise you need to learn about file locking to prevent votes from being lost if they happen simultaneously.

 

oh yup I do know what you meant so if there's another vote for metallic the number would be 3.

But honestly I'm quite new at all these and totally new to json and do know database is way better but I'm just doing it for fun as to learn too.

I was reading your reply but got even more lost on how to make it something like

 

{"metallic":2,"pop":1}
Link to comment
Share on other sites

Darn, I missed that. I seem to be missing alot the last couple of days.

 

Well in that case just grab the value of the 'type' field and use it as an index in the count array:

 

$counts = array('foo'=>0,'bar'=>0,'wibble'=>0);

 

// loop

$count[$value_from_json]  += 1;

 

and at the end:

var_dump($count);

thanks a lot... I will try to digest that and try it sometime tomorrow. Hopefully I can get it to work.

You guys are so nice!~

 

P.S.

where do you get the

 

$value_from_json

sorry for my naive

Link to comment
Share on other sites

hopefully you guys don't mind me asking, I know earlier vinny42 said it's not valid json and I searched and posted around too and others said that too but then in my coding I did use json to encode and then use json to decode and in my json file it says

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

and I figured people are saying it's invalid because it should look like

[
{"type":"metallic"},
{"type":"pop"},
{"type":"metallic"}
]

people are saying this is the invalid way but I didn't code those into the json the script automatically did.

 

even when I searched w3school the example of json is

 

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

  Did I do something wrong here?

Edited by et4891
Link to comment
Share on other sites

data.json contains valid json data on each line. All you need to do is loop through each line and parse the json data. Assign each type to a $votes array. Then count the values. Example code

$file = file('data.json'); // each line gets added to the $file array
 
$votes = array(); // initiate $votes to an array
foreach($file as $line) {
$vote = json_decode($line, true); // json decode current line
 
$votes[] = $vote['type']; // add vote to array
}
 
// display votes count
echo '<pre>'.print_r(array_count_values($votes)],1).'</pre>';
Link to comment
Share on other sites

 

data.json contains valid json data on each line. All you need to do is loop through each line and parse the json data. Assign each type to a $votes array. Then count the values. Example code

$file = file('data.json'); // each line gets added to the $file array
 
$votes = array(); // initiate $votes to an array
foreach($file as $line) {
$vote = json_decode($line, true); // json decode current line
 
$votes[] = $vote['type']; // add vote to array
}
 
// display votes count
echo '<pre>'.print_r(array_count_values($votes)],1).'</pre>';

ah ok then after the numbers are in the $votes as an array I can use something like array_reduce to get just the numbers and echo the numbers only if I want right?

Link to comment
Share on other sites

Yeah you can do that. As one line in the within the foreach loop

$file = file('data.json'); // each line gets added to the $file array
 
$votes = array(); // initiate $votes to an array
foreach($file as $line) {
$vote = json_decode($line, true); // json decode current line
$votes[ $vote['type'] ]++; // add vote to array
}
 
// display votes count
echo '<pre>'.print_r($votes],1).'</pre>';

My orginal code adds all vote types to an array as a new item. I then count the votes using the array_count_values function. Which will give the exact same result as above.

Edited by Ch0cu3r
Link to comment
Share on other sites

Ch0cu3r>

somehow this didn't work.

This gives out error for undefined index:metallic

$votes[ $vote['type'] ]++;

the previous one works well though gives this

Array
(
    [metallic] => 2
    [pop] => 1
)

But I'm really sorry :( first time making array like this...so now I only want to print the number 2

I thought normally something like $votes[0] would echo the number and I tried something like $vote[0] or $vote['metallic'] might work but guess I'm wrong....

 

P.S. Thanks guys.  Really sorry for all the trouble....thought this would be something fun for myself to do and learn.

Edited by et4891
Link to comment
Share on other sites

$x++ is like saying $x = $x + 1. So

$votes[ $vote['type'] ] = $votes[ $vote['type'] ] + 1;
Now do you see where the "undefined index" comes from? You're trying to +1 a value in an array that doesn't exist.

 

You need an isset() check to either +1 (if it already exists) or create it (if it doesn't exist yet).

Link to comment
Share on other sites

$x++ is like saying $x = $x + 1. So

$votes[ $vote['type'] ] = $votes[ $vote['type'] ] + 1;
Now do you see where the "undefined index" comes from? You're trying to +1 a value in an array that doesn't exist.

 

You need an isset() check to either +1 (if it already exists) or create it (if it doesn't exist yet).

 

ah alright....damn how can I miss such obvious thing...

but somehow I kept on trying and trying and still couldn't just echo the vote number :(

Link to comment
Share on other sites

  • Solution

Ch0cu3r>

somehow this didn't work.

This gives out error for undefined index:metallic

$votes[ $vote['type'] ]++;

 

First you'll need check if the key exits then initiate it.

$key = $vote['type'];     // use the vote as the key
if(isset($votes[ $key ])) // check if current vote exits. If it does increment vote by 1
    $votes[ $key ]++;
else                      // vote doesn't exist yet. Add vote to votes (creates new key). Initiate vote with 1
    $votes[ $key ] = 1;

To display the result of the votes rather than echo '<pre>'.print_r($votes],1).'</pre>'; You can do

echo "<h1>Vote Results</h1>";
foreach($votes as $vote => $count)
{
    echo "<b>$vote</b> has $count votes<br />";
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.