not sure how to explain this perfectly but I had some help from others earlier then I started thinking more and having more questions while I fool around with the codes…
I’m creating something like voting system and saves the data in data.json since I’m just fooling around and heard using json is a good simple way to start so I didn’t create a database and so on.
my index page was just a two radio buttons to choose and then submit then the data stores into data.json and here is the example of my data.json
{"type":"left"}
{"type":"left"}
{"type":"right"}
I got some help from few super nice people to figure out how I can run script and count how many left and how many right but then now I got another idea is if I only want to show how many left or only how many right or if I added more into the option and I only want a few certain # to show instead of all.
for example there are two left being submitted and I only want to show 2 instead of showing
left 2
right 1
I only want to show 2 for I don’t know what reason or just show 1 maybe to explain different thing or blah…
here is my code to count how many left and right
$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
$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;
}
echo "<h1>Vote Results</h1>";
foreach($votes as $vote => $count)
{
echo "<b>$vote</b> has $count votes<br />";
}
I tried something like $count[0] and things like that which is how we normally recall a certain string in an array but $count[0] $votes[0] $vote[0]
.
Can someone give me a hand? Really thanks…