I've been struggling with the following code. What I'm trying to do is count the number of reviews based on the score. The information is being drawn from MYSQL and a calculation is being preformed before entering it to an array there will be a maximum of five results (after formatting). To be counted.
The code I have is as follows:
$myArray = str_split(554);
$newArray = array_count_values($myArray);
foreach ($newArray as $key => $value) {
$reviews_percentage = round($value/3*100);
if (array_key_exists("1",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "1 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("2",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "2 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("3",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "3 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("4",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "4 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("5",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "5 - <strong>0</strong> as a percent its : 0 <br />";
}
}
Which is giving the following result:
1 - 0 as a percent its : 0
2 - 0 as a percent its : 0
3 - 0 as a percent its : 0
5 - 1 as a percent its : 50
5 - 1 as a percent its : 50
1 - 0 as a percent its : 0
2 - 0 as a percent its : 0
3 - 0 as a percent its : 0
4 - 1 as a percent its : 50
4 - 1 as a percent its : 50
I can see its running through the loop twice but cannot work out what I'm doing wrong.
Added Database Structure
|------
|id|date_created|date_updated|ip_address|status|element_3|element_4|element_5|element_6|element_7|element_8|element_9|
|------
|1|2012-06-21 15:22:57|2012-06-21 16:06:04|::1|1|19|10|10|10|10|10|10|
|2|2012-06-21 16:21:23|2012-06-21 16:21:40|::1|1|19|10|9|9|9|10|
|3|2012-06-21 18:14:56|2012-06-21 18:15:19|::1|1|18| 5|5|5|5|5|
UPDATED CODE
$result = mysql_query("SELECT * FROM ap_form_5 WHERE element_1='19'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($profile_rows = mysql_fetch_array($result)) {
$feature1 = $profile_rows['element_4'];
$feature2 = $profile_rows['element_5'];
$feature3 = $profile_rows['element_6'];
$feature4 = $profile_rows['element_7'];
$feature5 = $profile_rows['element_8'];
$overalladd = $feature1+$feature2+$feature3+$feature4+$feature5;
$ratingsbar .= floor(round($overalladd/5/2, 15, PHP_ROUND_HALF_DOWN));
$myArray = str_split($ratingsbar);
$arrayCount = array_count_values($myArray);
}
function perc($total,$count){
$ans = (100/$total) * $count;
return($ans);
// this array is only being filled like this to to show my working out (your db will populate this)
$ratings[1]= $arrayCount[0]; // 1 star ratings - 2 votes
$ratings[2]= $arrayCount[1]; // 2 star rating - 1 votes
$ratings[3]= $arrayCount[2]; // 3 star rating - 2 votes
$ratings[4]= $arrayCount[3]; // 4 star rating - 0 votes
$ratings[5]= $arrayCount[4]; // 5 star rating - 5 votes
$total_votes = array_sum($ratings);
$i = 1;
foreach($ratings as $rating){
echo "Stars ".$i.": ".perc($total_votes,$rating)."% $ratings[$i]<br />";
$i ++;
}
?>
Which is now giving the following result
Stars 1: 0%
Stars 2: 0%
Stars 3: 50% 1
Stars 4: 0%
Stars 5: 50% 1
Give this a try?
<?php
$result = mysql_query("SELECT * FROM ap_form_5 WHERE element_1='19'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($profile_rows = mysql_fetch_array($result)) {
$total_ratings_this_loop = 0; // empty this before looping
$ratings[1]= $profile_rows['element_4']; // assuming that this field contains 1 star ratings for this product
$ratings[2]= $profile_rows['element_5']; // assuming that this field contains 2 star ratings for this product
$ratings[3]= $profile_rows['element_6']; // assuming that this field contains 3 star ratings for this product
$ratings[4]= $profile_rows['element_7']; // assuming that this field contains 4 star ratings for this product
$ratings[5]= $profile_rows['element_8']; // assuming that this field contains 5 star ratings for this product
$total_ratings_this_loop = array_sum($ratings); // takes all of the ratings for this product and totals them from inside the array
$overalladd = $feature1 + $feature2 + $feature3 + $feature4 + $feature5;
echo "Product ID: 19, has the following ratings<br />";
$i = 1; // empty this before looping
foreach($ratings as $rating_count){
echo $i." star, Rating count: ".$rating.",Percentage:".perc($total_ratings_this_loop,$rating)."%<br />";
$i ++;
}
}
?>
Replace your code with below code and check :
$myArray = str_split($ratingsbar);
$newArray = array_count_values($myArray);
foreach ($myArray as $key => $value) {
$reviews_percentage = round($value/$num_rows*100);
if (array_key_exists("1",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "1 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("2",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "2 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("3",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "3 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("4",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "4 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("5",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "5 - <strong>0</strong> as a percent its : 0 <br />";
}
}
What I'm trying to do is count the number of reviews based on the
score.
Please show us the database structure filled with minimized example data, and tell us what is your expected result according to that data.
OK, if you would like to create something like this:
then I demostrate, how I would do it, because I still does not understand your logic.
votes table (this means user U voted on product P with S stars):
user_id | product_id | star
1 1 5
2 1 5
3 1 4
4 1 1
sql query for total votes on product 1 is
SELECT star,COUNT(*) as C
FROM votes
WHERE product_id=1
GROUP BY star
the result of this is
star C
1 1
4 1
5 2
to write it out:
$rs = mysql_query("");//put query here
$stars_count = array();
$star_sum = 0;
while($r = mysql_fetch_assoc($rs))
{
$stars_count[$r['star']] = $r['C'];
$star_sum += $r['C'];
}
for($i=5;$i>=1;$i--)
echo "Product 1 was voted $i star: ".
(isset($stars_count[$i])? round($stars_count[$i]/$star_sum*100)."%":"0%").
" (".( isset($stars_count[$i])? $stars_count[$i] : 0 ).")<br>";
result:
Product 1 was voted 5 star: 50% (2)
Product 1 was voted 4 star: 25% (1)
Product 1 was voted 3 star: 0% (0)
Product 1 was voted 2 star: 0% (0)
Product 1 was voted 1 star: 25% (1)
Related
I am getting output:
"Your number is 49
Your number is 50
Not possible"
But why?What is the if-else statement say in here. How the pre and post increment works here?
<?php
$num = 49;
if($num % 2)
{
echo "Your number is ";
echo($num);
}
if($num++ % 3)
{
echo "Your number is ";
echo($num);
}
if(++$num % 3)
{
echo "Your number is ";
echo($num);
}
else
echo "Not possible";
In php boolean expression returns 1 for true and 0 for false
So in first if 49 % 2 return 1 so that block will execute
Second if also execute like first one and then num incremented and becomes 50
In 3rd if first num incremented then calculate 51 % 3 which returns 0 so the else block executes
<?php
$num = 49; // num is 49
if($num % 2) // 49%2 = 1 so basically true
{
echo "Your number is ";
echo($num); // print 49
}
if($num++ % 3) // (49++ = 50 % 3 = 2) post increment basically u r setting $num = $num+1
{
echo "Your number is ";
echo($num); //print 50
}
if(++$num % 3) // pre increment (51%3 = 0) basically false
{
echo "Your number is ";
echo($num);
}
else
echo "Not possible"; // so it show this
Consider I have a following array of total scores, with each value being a score of a player in a tournament.
$total_scores = array(350,200,150,150,75,75,75,0);
I need to create a table, which lists the players with correct positions, if they have the same score, the listing should reflect this, ie.:
1. Player 1 350
2. Player 2 200
3.-4. Player 3 150
3.-4. Player 4 150
5.-7. Player 5 75
5.-7. Player 6 75
5.-7. Player 7 75
8. Player 8 0
I tried to do something with
foreach ($total_scores as $total_score) {
$no_of_occurrences = array_count_values($total_scores)[$total_score];
}
But cannot figure out how to build the correct positions numbering.
<?php
$scores = array(350,200,150,150,75,75,75,0); //assuming you have sorted data otherwise you need to sort it first
$count = array();
$startIndex = array();
$endIndex = array();
$len = count($scores);
for($i = 0; $i < $len; $i++){
if(!isset($count[$scores[$i]])){
$count[$scores[$i]] = 1;
$startIndex[$scores[$i]] = $endIndex[$scores[$i]] = $i+1;
}else{
$count[$scores[$i]]++;
$endIndex[$scores[$i]] = $i+1;
}
}
$i = 1;
foreach($scores as $s){
echo $startIndex[$s].'.';
if($startIndex[$s] != $endIndex[$s]){
echo '-'.$endIndex[$s].'.';
}
echo ' Player '.$i.' '.$s."\n"; //if newline not works try echoing <br>
$i++;
}
Working Demo
For this Array needs to be sorted in descending order
$total_scores = array(350, 200, 150, 150, 75, 75, 75, 0);
rsort($total_scores);
$no_of_occurrence = array_count_values($total_scores);
array_unshift($total_scores, ""); // For starting count from 1
unset($total_scores[0]); // For starting count from 1
$i = 1;
foreach ($total_scores as $key => $value)
{
$position = array_keys($total_scores,$value);
if($no_of_occurrence[$value] == 1)
{
echo "Position " . $i . " ";
echo "Player " . $i . " " . $value . " ";
}
else
{
echo "Position " . $position[0] . " - " . end($position) . " ";
echo "Player " . $i . " " . $value . " ";
}
$i++;
echo "<br>";
}
Output of above code :
Position 1 Player 1 350
Position 2 Player 2 200
Position 3 - 4 Player 3 150
Position 3 - 4 Player 4 150
Position 5 - 7 Player 5 75
Position 5 - 7 Player 6 75
Position 5 - 7 Player 7 75
Position 8 Player 8 0
How can I detect 2nd and 3rd iteration
Here's what I did but It doesn't give the right answer
$sample_array = array('boom 1','boom 2','boom 3','boom 4','boom 5','boom 6','boom 7');
$separator2 = 0;
$separator3 = 0;
foreach($sample_array as $sample_array_value){
if(++$separator3 % 3 == 0)
{
echo $sample_array_value."<br /><br /> Separator 3 <br /><br />";
}
else if(++$separator2 % 2 == 0)
{
echo $sample_array_value."<br /><br /> Separator 2 <br /><br />";
}
else
{
echo $sample_array_value."<br />";
}
}
the output of that code is:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
boom 5
Separator 2
boom 6
Separator 3
boom 7
Which is wrong, I need the output to be:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
Separator 2
boom 5
boom 6
Separator 2
Separator 3
boom 7
You don't need extra variables, since your array is 0-based indexed, you can just use the key. Also you have to change your logic a bit, so that you get your expected output, e.g.
foreach($sample_array as $key => $sample_array_value){
echo $sample_array_value . "<br />";
if(($key + 1) % 2 == 0 && ($key + 1) % 3 == 0)
echo "<br>Separator 2 <br />Separator 3<br /><br />";
elseif(($key + 1) % 2 == 0)
echo "<br>Separator 2 <br /><br />";
elseif(($key + 1) % 3 == 0)
echo "<br>Separator 3 <br /><br />";
}
output:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
Separator 2
boom 5
boom 6
Separator 2
Separator 3
boom 7
You're suppose to check for 2nd and 3rd outside the if that implements the boom. since you also want the separator to be done after the boom, then bring it down.
$sample_array = array('boom 1','boom 2','boom 3','boom 4','boom 5','boom 6','boom 7');
$separator2 = 0;
$separator3 = 0;
$count = 1;
foreach($sample_array as $sample_array_value){
echo $sample_array_value."<br />";
if($count % 3 == 0)
{
echo "Separator 3 <br />";
}
if($count % 2 == 0)
{
echo "Separator 2 <br /><br />";
}
$count++;
}
I have this cod for my TOP LIST
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
data[1] is NAME
data[2] is SURNAME
sms[vote] is NUMBER OF VOTES
And these top list look like this
1 Novak Djokovic 50
2 Rafael Nadal 35
3 Roger Federer 30
4 Andre Agassi 26
5 Pete Sampras 22
6 Andy Murray 19
7 Chris Evert 13
8 Michael Chang 10
9 Andy Roddick 7
10 Boris Becker 5
11 Björn Borg 1
And I want my top list look like this
// FINALIST // Limit first 4 // green font
1 Novak Djokovic 50
2 Rafael Nadal 35
3 Roger Federer 30
4 Andre Agassi 26
// OTHERS // All other except first 4 and last 2 // black font
5 Pete Sampras 22
6 Andy Murray 19
7 Chris Evert 13
8 Michael Chang 10
9 Andy Roddick 7
// FALL OUT // Limit last 2 // red font
10 Boris Becker 5
11 Björn Borg 1
I hope you understand me and that someone knows how to solve this problem.
Thank you.
You can use this code:
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
$max = mysql_num_rows($upit);
$max = $max - 2;
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// first 4 in different color. Green Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos <= $max) {
//from 5th to 3rd last (left 2 from bottom) in different color. Black Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// last 2 in different color. Red Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}
My guess is you're wanting something like this... you can then change your echo code based on how you want to format it.
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// finalist format (1-4)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos > 9) {
// format fallout users (9+)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// format other (5-9)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}
Assuming first 4 in different color, from 5th to 3rd last (left 2 from bottom) in different color and last 2 in different color.
So, first find total number of row from SQL query so that we can put 2nd if condition.
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
$max = mysql_num_rows($upit);
$max = $max - 2;
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// first 4 in different color. Green Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos <= $max) {
//from 5th to 3rd last (left 2 from bottom) in different color. Black Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// last 2 in different color. Red Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}
Assuming you need HTML output, here is a very crude way of doing it:
<?php
$pos = 0;
if( $upit = mysql_query( "SELECT * FROM wp_entries ORDER BY vote DESC" ) )
{
$num_rows = mysql_num_rows( $upit );
if( $num_rows > 0 )
{
echo '<ul>';
while ($sms = mysql_fetch_array($upit))
{
$pos++;
$style = "";
if ($pos < 5)
{
$style = ' style="color:#00FF00;"';
}
elseif ($pos <= ($num_rows-2))
{
$style = ' style="color:#000000;"';
}
else
{
$style = ' style="color:#FF0000;"';
}
$data = unserialize($sms['data']);
echo ' <li'.$style.'>'.$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms['vote']."<li>";
}
echo '<ul>';
}
}
?>
I'm not really sure how to work this question, but I currently have a while loop outputting <li></li>.
Let's say that there are 35 rows and I want the counter to increase every five times.
So the output would be something like this.
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 4 Name and so on...
I've tried counting throughout the loop and comparing the number to see if it was less than five and if not then increasing it, but I know that's not correct. Just can't seem to figure out the best solution.
while ($stmt->fetch()) {
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
To try to make this clearer...basically I would like to have a counter variable running. Starting at 1, but every fifth time through the while loop, I would like to increase this count variable by one.
$count = $rows = 0;
while ($stmt->fetch()) {
if ($rows % 5 == 0)
$count++;
$rows++;
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
You could use array_fill() (psuedo code):
<?php
$li = "<li>Item</li>";
$row = array_fill(0, 5, $li);
$list = array_fill(0, 35, $row);
print_r($list);
?>
http://codepad.org/ETCv3GBK
As in:
$count = 0;
while ($stmt->fetch() && $count++) {
$HTML .= implode('', array_fill(0, 5, "<li data-id='$id' data-name='$name'>$count Name</li>"));
}
Another demo (ignite.io may not be working on save, though):
https://ignite.io/code/514a9bf5ec221ee821000005
for($i=1; $i <= 20; $i++){
$array[] = "Name " . $i;
}
$count = 1;
$output = 1;
for($i=0; $i < 20; $i++){
if($count++ < 5)
echo $output . ". " . $array[$i] . "<BR>";
else{
$count = 1;
echo $output++ . ". " . $array[$i] . "<BR>";
}
}
returns
Name 1
Name 2
Name 3
Name 4
Name 5
Name 6
Name 7
Name 8
Name 9
Name 10
Name 11
Name 12
Name 13
Name 14
Name 15
Name 16
Name 17
Name 18
Name 19
Name 20
$i=1
while ($stmt->fetch()) {
if($i%5==0){
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
$i++;
}