how to choose ONLY certain value in an array? ($count[0] doesn't work)

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…

When you set an array key ($votes[ $key ]) you must use this key to fetch it again. Example:
[php]<?php
$array = array();
$array[] = ‘foo’;
echo $array[0]; //prints foo

$array[‘bar’] = 123;
echo $array[‘bar’]; // prints 123[/php]

[hr]

For this task I would really do something like this:

store a json like this:
[php]{“alternatives”:{“left”:0,“right”:0},“votes”:[]}[/php]

Then I would do something like this:
[php]<?php

// this should ofcourse be changed to your user-stuff
$loggedInUser = array(
‘id’ => rand(1000,6000)
);

function getFromStore() {
return json_decode(file_get_contents(‘data.json’));
}

function saveToStore($data) {
file_put_contents(‘data.json’, json_encode($data));
}

if (!empty($_POST[‘vote’])) {
$data = getFromStore();
// Ok, let’s do some voting
if (empty($data->alternatives->$_POST[‘vote’])) {
echo ‘

INVALID VOTE

’;
} else {
$data->alternatives->$_POST[‘vote’]++;
$data->votes[] = array(
‘time’ => date(“Y-m-d H:i:s”),
‘userId’ => !empty($loggedInUser[‘id’]) ? $loggedInUser[‘id’] : ‘Guest’,
‘vote’ => $_POST[‘vote’]
);
saveToStore($data);
// Do a redirect to clear post (if you do not redirect you will resubmit the form if you press F5 / reload.
header(‘Location: http://’ . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI]);
}
}

$data = getFromStore();
rsort($data->votes);
?>

<?php foreach ($data->alternatives as $alternative => $count) { ?> <?= ucfirst($alternative) ?>
<?php } ?>

Vote Results

<?php foreach($data->alternatives as $alternative => $count) { ?> <?= $alternative ?> has <?= $count ?> votes
<?php } ?>

Votes

<?php foreach($data->votes as $vote) { ?> <?= $vote->time ?> : User <?= $vote->userId ?> voted <?= $vote->vote ?>
<?php } ?>[/php]

Output:

Vote Results left has 4 votes right has 3 votes

Votes
2013-09-25 08:43:38 : User 4455 voted left
2013-09-25 08:43:36 : User 1805 voted left
2013-09-25 08:43:34 : User 4183 voted right
2013-09-25 08:40:58 : User 3932 voted right
2013-09-25 08:40:03 : User 5315 voted left
2013-09-25 08:39:58 : User 4238 voted right
2013-09-25 08:39:53 : User 3823 voted left

JSON store now looks like this:

{ "alternatives": { "left": 4, "right": 3 }, "votes": [ { "time": "2013-09-25 08:39:53", "userId": 3823, "vote": "left" }, { "time": "2013-09-25 08:39:58", "userId": 4238, "vote": "right" }, { "time": "2013-09-25 08:40:03", "userId": 5315, "vote": "left" }, { "time": "2013-09-25 08:40:58", "userId": 3932, "vote": "right" }, { "time": "2013-09-25 08:43:34", "userId": 4183, "vote": "right" }, { "time": "2013-09-25 08:43:36", "userId": 1805, "vote": "left" }, { "time": "2013-09-25 08:43:38", "userId": 4455, "vote": "left" } ] }

ah ok I get what you mean now but when I use echo $votes[ $key ]; only 7 is printed instead of saying it’s an array how can I then only print the vote 3 then?
Sorry I’m still quite new…and always when I’m stuck my brain just feels like it’s clogged even if it’s some simple thing it’s just clogged and won’t open up easily :frowning:
seeing your $array['bar'] example I used $votes[ $key ] to give it a try and 7 is printed I thought an array will show and say it’s an array that I have to do something like $votes[ $key ][0] for 7 to be printed but I’m wrong again :frowning:

It’s kinda hard to understand what you mean. You can’t echo an array, echoing an array key will always give you the value assigned to that key. Doing a foreach and breaking up arrays into key => value should work (like you do)

This works perfectly:
[php]<?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

foreach ($array as $alt => $votes) {
echo $alt . ’ has ’ . $votes . ’ votes
’;
}[/php]

Output:

test1 has 7 votes test2 has 8 votes test3 has 9 votes
[hr]

If you are having trouble you just have to start debugging, either with tools or by trying to var_dump your arrays/values.

Tip: adding a pre tag makes reading dumps much easier. Compare:
[php]<?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

var_dump($array);

echo ‘

’;
var_dump($array);[/php]

Output:

[code]array(3) { [“test1”]=> int(7) [“test2”]=> int(8) [“test3”]=> int(9) }

array(3) {
[“test1”]=>
int(7)
[“test2”]=>
int(8)
[“test3”]=>
int(9)
}[/code]

Oh man, I’ve spent way too much time on this now… But this works, kinda fun to work with something non-oop again (even though I could hardly resist converting it)

Note: if you try this you should change isAdmin to true to get the admin controls.

[php]<?php

// this should ofcourse be changed to your user-stuff
$loggedInUser = array(
‘id’ => rand(1000,6000),
‘isAdmin’ => false
);

/********************************************************

  • Functions
    ********************************************************/

function getFromStore() {
return json_decode(file_get_contents(‘data.json’));
}

function saveToStore($data) {
file_put_contents(‘data.json’, json_encode($data));
// Do a redirect to clear post (if you do not redirect you will resubmit the form if you press F5 / reload.
header(‘Location: http://’ . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI]);
}

function vote($vote, $userId = ‘Guest’) {
$data = getFromStore();
// Ok, let’s do some voting
if (!isset($data->alternatives->{$vote})) {
echo ‘

VOTE ALTERNATIVE DOES NOT EXIST

’;
} else {
$data->alternatives->$vote++;
$data->votes[] = array(
‘time’ => date(“Y-m-d H:i:s”),
‘userId’ => $userId,
‘vote’ => $vote
);
saveToStore($data);
}
}

function createAlternative($alternative) {
$data = getFromStore();
if (isset($data->alternatives->$alternative)) {
echo ‘

ALTERNATIVE ALREADY EXIST

’;
}
$data->alternatives->$alternative = 0;
saveToStore($data);
}

function deleteAlternative($alternative) {
$data = getFromStore();
if (!isset($data->alternatives->$alternative)) {
echo ‘

ALTERNATIVE DOESN’T EXIST

’;
}
unset($data->alternatives->$alternative);
saveToStore($data);
}

function deleteVotes() {
$data = getFromStore();
foreach ($data->alternatives as $alternative => $value) {
$data->alternatives->$alternative = 0;
}
$data->votes = array();
saveToStore($data);
}

/********************************************************

  • Logic
    ********************************************************/

$errors = array();

if (!empty($_POST[‘vote’])) {
vote($_POST[‘vote’], $loggedInUser[‘id’]);
}

if (!empty($_POST[‘create_alternative’]) && $loggedInUser[‘isAdmin’]) {
createAlternative($_POST[‘create_alternative’]);
}

if (!empty($_POST[‘delete_alternative’]) && $loggedInUser[‘isAdmin’]) {
deleteAlternative($_POST[‘delete_alternative’]);
}

if (!empty($_POST[‘delete_votes’]) && $loggedInUser[‘isAdmin’]) {
deleteVotes();
}

/********************************************************

  • View
    ********************************************************/
    $data = getFromStore();
    rsort($data->votes);
    ?>
<?php if (count(get_object_vars($data->alternatives)) < 1) { ?>

No alternatives registered :frowning:

<?php } else { ?> <?php foreach ($data->alternatives as $alternative => $count) { ?> <?= ucfirst($alternative) ?>
<?php } ?> <?php } ?>

Vote Results

<?php foreach($data->alternatives as $alternative => $count) { ?> <?= $alternative ?> has <?= $count ?> votes
<?php } ?>

Votes

<?php foreach($data->votes as $vote) { ?> <?= $vote->time ?> : User <?= $vote->userId ?> voted <?= $vote->vote ?>
<?php } ?> <?php if (empty($data->votes)) { ?>

No votes yet :frowning:

<?php } ?> <?php if ($loggedInUser['isAdmin']) { ?>

Admin stuff

<?php foreach($data->alternatives as $alternative => $count) { ?> <?= ucfirst($alternative) ?> <?php } ?> <?php } ?>[/php]


ah sorry for my poor english. Earlier I was just trying to try and create a script like my first post which is completed. But now I have another idea is that if I’m doing a 2d canvas pie chart to draw the percentage. I already figured how the 2d canvas can be done but I only need the votes of the left/right.

so let’s say if left have 3 votes and right has 1 votes but I need only the 3 and 1 value to carry into the variables I’m using in the 2d canvas to draw the piechart.

that’s why I want to try and only echo the number one by one.
Hopefully I’m making this more clear what I want to try. Sorry for any confusions.

This echoes both key and value:
[php]<?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

foreach ($array as $alt => $votes) {
echo $alt . ’ has ’ . $votes . ’ votes
’;
}[/php]

If you only need values:
[php]<?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

foreach ($array as $votes) {
echo $votes . ‘
’;
}[/php]

For a chart you could probably also do this and insert it straight into the chart settings:
[php]<?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

echo implode(’,’, $array); // 7,8,9[/php]

ah ok…I will try echo implode(',', $array); // 7,8,9 tomorrow or something because I think this is what I didn’t try yet but the thing is…
for the previous samples you gave me for echoing both key and value and echo only values, I totally understand how those sample works but just somehow when I’m trying to get like what I said before and by using your example

[code] <?php
$array = array(
‘test1’ => 7,
‘test2’ => 8,
‘test3’ => 9
);

foreach ($array as $votes) {
  echo $votes . '<br />';

}[/code]

I only want to get the number 8 from test2 and nothing else so I try to pass (not sure I know how it can be done yet) value 8 into the chart’s calculation.

Then do:
[php]echo $array[‘test2’];[/php]

As I said in my original answer.

[quote author=JimL link=topic=21514.msg74353#msg74353 date=1380091725]
When you set an array key ($votes[ $key ]) you must use this key to fetch it again. Example:
[php]<?php
$array = array();
$array[] = ‘foo’;
echo $array[0]; //prints foo

$array[‘bar’] = 123;
echo $array[‘bar’]; // prints 123[/php]

JimL>

OMG thanks OMG what was I thinking!
arg >.<"

Thanks a lot…

P.S. is there a way to say this forum is solved or give you a thumbs up? Sorry totally new in this forum.

I marked it as answered for you :slight_smile: Think you need more posts/points/whatever to unlock some more features.

again thanks for the help. I kept on thinking I tried that too, I guess I tried that with the wrong variable or something gosh…took me hours to figure out and asking around. Thanks thanks

ah~! not sure if you are still reading this post but one more stupid question that I kept on forgetting to ask…for the examples…left right up were used and as I said I was trying to bring the result and make it into a pie chart. I kept forgetting to ask what if in my json there were only left and right data in it without up then when I open up the data.json up weren’t there I need to find a way to set it so if some exist value is not inside the data then the value is 0.

Sponsor our Newsletter | Privacy Policy | Terms of Service