Hi guys I'm doing arrays for PHP that list all the column output and get the average of test scores but I can't seem to figure out the logic to get the average of each column. But I'm not too sure if I'm doing it right or wrong because my output for average is all 0 and I don't know how to change it to read the value and make it calculate.
Much appreciate it if you can help. Thank you.
Basically, I want the output to be like this;-
RM = Physics : 35, Maths : 30, Chemistry : 39, English : 80,
RM Average Scores: 46
Justin = Physics : 61, Maths : 10, Chemistry : 45, English : 33,
Justin Average Scores: 37.25
Miley = Physics : 25, Maths : 100, Chemistry : 88, English : 60,
Miley Average Scores: 68.25
This is my array:-
<?php
$students = array(
"RM" => array("test1" => 35, "test2" => 30,"test3" => 39, "test4" => 80),
"Justin" => array("test1" => 61, "test2" => 10,"test3" => 45, "test4" => 33),
"Miley" => array("test1" => 25, "test2" => 100,"test3" => 88, "test4" => 60),
);
?>
This is my code:-
<table style="border: 1px solid black">
<?php
echo "<td><p><b>Listing All Student Tests and Scores:-</b></p></td>";
$the_students = array_keys($tudents);
for($i = 0; $i < count($students); $i++) {
echo "<tr>";
// Output All Data
echo "<td><b>". $the_students[$i] . "</b>" . " = ";
foreach($students[$the_students[$i]] as $student => $score) {
echo "<b>". $student ."</b>". " : " . $score. ", ";
}
echo "<br>";
// Average Output
echo "<b>". $students[$i]. " Average Scores</b>: ";
if (array_key_exists($i, $the_students)) {
echo average_scores($students, $the_students);
}
echo "</td>";
echo "</tr>";
}
?>
</table>
I use function and put it at the end of my code:-
<?php
function average_scores($students, $i) {
$total = 0;
$students = array();
foreach ($students as $student => $data) {
$total += $data[$i];
}
return $total / 4;
}
?>
Since you are already looping, try like this
<table style="border: 1px solid black">
<?php
echo "<td><p><b>Listing All Student Tests and Scores:-</b></p></td>";
$the_students = array_keys($tudents);
for($i = 0; $i < count($students); $i++) {
$total = 0;
echo "<tr>";
// Output All Data
echo "<td><b>". $the_students[$i] . "</b>" . " = ";
foreach($students[$the_students[$i]] as $student => $score) {
$total += $score;
echo "<b>". $student ."</b>". " : " . $score. ", ";
}
echo "<br>";
// Average Output
echo "<b>". $students[$i]. " Average Scores</b>: ";
echo $total/ count($students[$the_students[$i]]);
echo "</td>";
echo "</tr>";
}
?>
</table>
The best practice would be to keep HTML and PHP code separate. Use the PHP marking whenever needed, it will improve the code readability EG:
echo "<b>". $students[$i]. " Average Scores</b>: ";
// convert to
<b><?php $students[$i]; ?> Average Scores</b>:
Try foreach to loop through students get the name which is the key and get also the student which is associative array, get only the values grades of student and destruct them into variables, printf to print them out in more readable format.
echo '<table style="border: 1px solid black">';
echo "<tr><th>Listing All Student Tests and Scores:-</th></tr>";
foreach ($students as $name => $student) {
$grades = array_values($student);
[$Physics, $Maths, $Chemistry, $English] = $grades;
echo "<tr><td>";
printf("%s = Physics : %d, Maths : %d, Chemistry : %d, English : %d<br>
%s Average Scores: %.2f"
,$name, $Physics, $Maths, $Chemistry, $English
,$name, average_scores($grades));
echo "</td></tr>";
}
echo "</table>";
For average you can use array_sum to sum all grades and divide them by their count.
function average_scores($grades) {
return array_sum($grades)/count($grades);
}
Related
I'm not too sure how to call the Associative array to verify if the number is true or false because I am doing a simple checker for enrollment class. The max class capacity is 40 and the file is combined with HTML and PHP.
I did it like this:-
<?php
//Create the association array.
$classInfo = array("J1" => 20 ,"J2" => 30,"J3" => 10,"J4" => 43,
"J5" => 40,"J6" => 45,"J7" => 15,"J8" => 34,"J9" => 10,"J10" => 45);
$class = array_keys($classInfo);
$totalEnroll = count($classInfo);
?>
The Code:-
<table width="300" style="border: 1px solid black">
<tr>
<?php
// class and enroll Lists
echo "<td width=20>";
echo "Class"."        "." Enroll"."<br><hr>";
for($i=0; $i < $totalEnroll; ++$i) {
echo $class[$i] . "     " .
$classInfo[$class[$i]] . "<br>";
}
echo "</td>";
// Enroll to check whether the classroom is full.
echo "<td width=20>";
echo "Class States" . "<br><hr>";
for($check = 0; $check < 10; $check++){
if($classInfo[$totalEnroll[$check]] >= 0 &&
$classInfo[$totalEnroll[$check]] <= 40){
echo "Full";
echo " <br>";
} else {
echo "Not Full";
echo " <br>";
}
}
echo "</td>";
?>
</tr>
</table>
The Output That I want:-
Class
Enroll
Full States
J1
20
Not Full
J5
40
Full
Do check on the part say `//Enroll to check whether the classroom is full. This is where the code of the enrollment class is checked.
However, by the way, the output can it be aligned more cleanly in a table-like column.
You are displaying the data in two separate loops which makes it difficult to align the data, you should make it into 1 loop and use the <tr> and <td> tags around each group of items...
<table width="300" style="border: 1px solid black">
<?php
foreach ( $classInfo as $className => $enrolled ) {
echo "<tr>";
// class and enroll Lists
echo "<td>{$className}</td>";
echo "<td>{$enrolled}</td>";
// Enroll to check whether the classroom is full.
echo "<td>";
if($enrolled <= 40){
echo "Full";
} else {
echo "Not Full";
}
echo "</td>";
echo "</tr>";
}
?>
</table>
(This doesn't include a header, but I'm sure you can add that).
Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>
I am creating an online grocery site where a user can enter his/her full name & address and then proceed to purchase groceries.
There are 20 grocery items to choose from - if the user wants an item, they can simply enter how many units of that item they want; this is the html code for for just 1 of the 20 items.
<tr>
<td> Milk - $3.99/carton </td>
<td> <input type="number" name="amtMilk" min=0> </td>
</tr>
At the bottom of the page there is a submit button which leads to a confirmation page in php. The confirmation page outputs the users name, address, all the items ordered and a total before and after tax.
I have written out the PHP for this however, it doesn't seem to be working correctly. Below is my code shortened to 4 items:
<?php
<h2> Customer Details: </h2>
<p>Customer Name: </p> echo $_POST['Name'];
<p>Address: </p> echo $_POST['Address'];
$total = 0;
<p>You ordered: </p>
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
foreach($POSTvalues as $key) {
if ($_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
elseif ($_POST['amtEggs'] > 0 ) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
elseif ($_POST['amtBread'] > 0 ) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
elseif ($_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total"; <br>
$afterTax = $total*0.13 + $total
$afterDelivery = $afterTax + 3.50
echo "Your total after tax is: $afterTax"; <br>
echo "Your total after delivery is: $afterDelivery";<br>
<h3> GRAND TOTAL: </h3> echo "$afterDelivery";
?>
Can anyone point out what i'm doing wrong or how I can fix this so get the desired output?
There is no need for the foreach loop, and thus no need for the $POSTvalues array.
Use independent if statements without the elseif.
A little psuedocode...
if (value1 > 0 )
{
add to total
print item
}
if (value2 > 0 )
{
add to total
print item
}
if (value3 > 0 )
{
add to total
print item
}
if (value4 > 0 )
{
add to total
print item
}
Fun fact: PHP turns elements with names structured like arrays into PHP arrays.
So, you can do this:
<?php
$array = array(
"milk" => array(
"price" => 3.99,
"unit" => "carton",
),
"eggs" => array(
"price" => 2.99,
"unit" => "dozen",
),
);
if (isset($_POST['amt'])) {
var_dump($_POST['amt']);
$total = 0;
foreach ($_POST['amt'] as $name=>$num) {
if($num > 0) {
$price = $array[$name]['price'];
$amt = $_POST['amt'];
$total += $price * $num;
echo $num . " " . ucfirst($name) . ", ";
}
}
echo "<br />Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo '<form method="POST"><button type="submit">Back</button></form>';
} else {
?><form method="POST"><table><?php
foreach ($array as $name=>$item) {
?>
<tr>
<td> <?php echo ucfirst($name); ?> - $<?php echo $item['price']; ?>/<?php echo $item['unit']; ?> </td>
<td> <input type="number" name="amt[<?php echo $name; ?>]" min=0> </td>
</tr><?php
}
?></table><input type="submit"></form><?php
}
I would consider either passing your price as a hidden field (for example, with the name price[milk]), or ensuring your array is available after you've submitted the form like I have done above. That way you don't have to hard-code in prices. The way you have it, it's going to be a nightmare to change if the prices change!
To add a new item, all you need to do is add a new key/array pair to the $array. No additional coding on the back-end. Just results.
Check it out here.
you're doing many things wrong.
so, how are you trying to display html inside php without using print/echo?
So here's revised code, hope this will resolve your issues.
<?php
echo '<h2> Customer Details: </h2>';
echo '<p>Customer Name: </p>'. $_POST['Name'];
echo '<p>Address: </p>'. $_POST['Address'];
$total = 0;
echo '<p>You ordered: </p>';
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
//foreach($POSTvalues as $key)
{
if (isset($_POST['amtMilk']) && $_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
if (isset($_POST['amtEggs']) && $_POST['amtEggs'] > 0) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
if (isset($_POST['amtBread']) && $_POST['amtBread'] > 0) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
if (isset($_POST['amtCereal']) && $_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo "<h3> GRAND TOTAL: </h3>$afterDelivery";
?>
EDIT
Comment out the foreach($POSTvalues as $key) and change all elseif to if.
add another condition in if statement like this && $_POST['amtCereal'] > 0 to ensure that it has value greater than 0
I've been around for years on Stack but this is my first time posting. I'm working on a website (php + mysql) and the following problem is driving me absolutely nuts.
I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:
SELECT Size, Amount FROM database WHERE product = 'product123' ORDER BY Size ASC
The php echo outputs an html table displaying Size and the corresponding available packs (Amount).
Echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>'
Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:
Size | Amount
1 | 10
1 | 50
2 | 10
2+ | 10
3 | 40
3+ | 25
3+ | 40
4+ | 25
What I'm looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:
Size | Amount
1 | 10 < yellow
1 | 50 < yellow
2 | 10 < transparent
2+ | 10 < yellow
3 | 40 < transparent
3+ | 25 < yellow
3+ | 40 < yellow
4+ | 25 < transparent
So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.
I can't figure out how to achieve this with php. The difficulty is that I can't use an evaluation based on odd/even since there sometimes is a "+" involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that "+" is not an option unfortunately.
I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can't figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.
Just a MCVE:
// your data
$records[] = array('size' => "1");
$records[] = array('size' => "1");
$records[] = array('size' => "2");
$records[] = array('size' => "2+");
$records[] = array('size' => "3");
$records[] = array('size' => "3+");
$records[] = array('size' => "3+");
$records[] = array('size' => "4");
$lastSize = $records[0]['size'];
$color = "yellow";
foreach ($records as $record) {
if ($lastSize != $record['size']) {
$lastSize = $record['size'];
if ($color == "yellow") $color = "transparent";
else $color = "yellow";
}
$lastSize == $record['size'];
echo $record['size'].' - '.$color.'<br>';
}
// OUTPUT:
// 1 - yellow
// 1 - yellow
// 2 - transparent
// 2+ - yellow
// 3 - transparent
// 3+ - yellow
// 3+ - yellow
// 4 - transparent
Ok, we'll start at the end. You probably want to put your color on the <tr>. The cleanest way to do it would be using css classes.
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
We'll figure out how to get the right value into $newSize in a moment. Next, we need the css for classes above, so make sure this is in your styles somewhere:
.transparentRow {
background-color: transparent;
}
.yellowRow {
background-color: yellow;
}
Ok, lets rip the + off the size:
$plainSize = trim($record['size'], '+')
Ok, we use that for comparison, using an ever changing $oldSize valiable. Here is a full, functional, block:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
$newSize = false;
} else {
$newSize = true;
}
$oldSize = $plainSize;
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
Some cleanup can lead to this:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
$oldSize = $plainSize;
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
I hope that helped not just with this problem, but with an example of how you can approach many other problems. Start at the end, work your way back.
As my comment suggested, use a double foreach() + implode() (and yet another solution):
<?php
$array[] = array("size"=>1,"amount"=>50);
$array[] = array("size"=>2,"amount"=>10);
$array[] = array("size"=>"2+","amount"=>10);
$array[] = array("size"=>3,"amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>"3+","amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>'4+',"amount"=>30);
// Sort by size
foreach($array as $row) {
$new[$row['size']][] = $row['amount'];
}
?>
<table>
<?php
$i = 0;
// Loop through the sorted groups
foreach($new as $size => $amts) {
// Determine odd or even
$color = ($i % 2 == 0)? "yellow":"transparent";
?> <tr>
<td class="<?php echo $color; ?>"><?php echo $size; ?></td>
<td class="<?php echo $color; ?>"><?php echo implode("</td>".PHP_EOL."</tr>".PHP_EOL."<tr>".PHP_EOL.'<td class="'.$color.'">'.$size.'</td><td class="'.$color.'">',$amts); ?></td>
</tr>
<?php $i++;
}
?>
</table>
You can do this using php sessions like this
session_start();
$_SESSION["pre_val"]='not set';
$_SESSION["pre_class"]='transparent';
//in your loop for showing table
//your loop starts
if($_SESSION["pre_val"]==$record['size']){
$suitable_class=$_SESSION["pre_class"];
}
else{
if($_SESSION["pre_class"]=='yellow'){$suitable_class='transparent';}
else{$suitable_class='yellow';}
}
//setting current values to session
$_SESSION["pre_class"] = $suitable_class;
$_SESSION["pre_val"] = $record['size'];
Echo '<tr class="$suitable_class"><td>'.$record['size'].'</td><td>'.$record['amount'].'</td></tr>';
//your loop ends
in your css
.yellow{background-color:yellow;}
.transparent{ background-color: rgba(255, 0, 0, 0.5);}
hope this solve your problem
Some for loop fun while printing out the table
$rows = array(
array("size"=>"1" ,"amount"=>"10"),
array("size"=>"1" ,"amount"=>"50"),
array("size"=>"2" ,"amount"=>"10"),
array("size"=>"2+","amount"=>"10"),
array("size"=>"3" ,"amount"=>"40"),
array("size"=>"3+","amount"=>"25"),
array("size"=>"3+","amount"=>"40"),
array("size"=>"4+","amount"=>"25")
);
echo "
<table>
<thead>
<tr><th>Size</th><th>Amount</th></tr>
</thead>
<tbody>";
$bgColors = ['transparent','yellow'];
$bgColor = 0;
echo "
<tr>
<td class='" . $bgColors[$bgColor] . "'>" . $rows[0]["size"] . "</td><td>" . $rows[0]["amount"] . "</td>
</tr>";
for($i = 1, $max = count($rows), $lastSize = $rows[0]; $i < $max; $lastSize = $rows[$i], $i++) {
if($rows[$i]["size"] !== $lastSize["size"])
$bgColor = ($bgColor + 1) % 2;
echo "
<tr>
<td style='background-color:" . $bgColors[$bgColor] . "'>" . $rows[$i]["size"] . "</td><td>" . $rows[$i]["amount"] . "</td>
</tr>";
}
echo "
</tbody>
</table>";
And an unasked for JS solution (assuming you've printed out the table as usual)
var rows = document.querySelectorAll('#sizeTable tbody td[name=size]');
var bgColors = ['transparent','yellow'];
var bgColor = 0;
for(var i = 1, lastSize = rows[0], max = rows.length; i < max; lastSize = rows[i],i++) {
if(rows[i].innerHTML !== lastSize.innerHTML) {
bgColor = (bgColor + 1) % 2;
}
rows[i].style['background-color'] = bgColors[bgColor];
}
you can keep the current size on a variable and if it changes you can change the color.
<html>
<head><title> Sample - Menukz </title></head>
<body>
<?php
/* Sample data array with size and amount */
$product['product123'] = array
(
array("size"=>"1", "amount"=>10),
array("size"=>"1", "amount"=>50),
array("size"=>"2", "amount"=>10),
array("size"=>"2+", "amount"=>10),
array("size"=>"3", "amount"=>40),
array("size"=>"3+", "amount"=>25),
array("size"=>"3+", "amount"=>40),
array("size"=>"4+", "amount"=>25)
);
$pre_size=0;
$pre_init=1;
echo "<table>";
foreach($product['product123'] as $row)
{
echo "<tr>";
/* Initialize */
if(strcmp($pre_size, $row['size']) !== 0 && $pre_init ===1)
{
$pre_size = $row['size'];
$pre_init = 0;
}
/* Change track */
if (strcmp($pre_size, $row['size']) !== 0 && $pre_init ===0)
{
echo "<td>Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
$pre_size = $row['size'];
}
else
{
echo "<td>Not Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
}
echo "</tr>";
}
?>
</body>
</html>
Thanks all for the proposed solutions. Berriel's MCVE works like a charm! However Stack doesn't let me +1 the answer yet.
I have one additional question:
I also have a second table in which the output of the first column can be any article code consisting of 10 chars limited to [a-z][0-9]. Since there is no predefined scheme such as in the Size table, I can't hardcode/predict any output like in most of the proposed solutions. However I still want to color the rows it in the same way described in my opening post.
I am not familiar with Stored Procedures or PDO in mysql. Is there any way to work around arrays with predefined content and still achieve the color grouping of rows with the same article code?
You can accomplish this using a nested repeat region.
First select your product by group WHERE product = 'product123' GROUP BY size
<?php
require ('conn.php');
try {
$prod = 'product123';
$sql = "SELECT * FROM sizes WHERE product=:prod GROUP BY size";
$query = $conn->prepare($sql);
$query->bindValue(':prod', $prod, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die('failed!');
}
?>
Then get all the products in each group ordered by amount inside a nested repeat region.
Each "grouped row" will alternate colors.
<table width="200" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Size</td>
<td>Amount</td>
</tr>
<?php
$i = 0;
do {
$i = $i + 1;
if ($i % 2 == 0){
echo '<tr bgcolor=#E4E4E4><td colspan="2">';
} else {
echo '<tr bgcolor=#EEEEEE><td colspan="2">';
}
try {
$group = $row['size'];
$sql = "SELECT * FROM sizes WHERE size=:group ORDER BY amount ASC";
$nested = $conn->prepare($sql);
$nested->bindValue(':group', $group, PDO::PARAM_INT);
$nested->execute();
$row_nested = $nested->fetch(PDO::FETCH_ASSOC);
$totalRows_nested = $nested->rowCount();
} catch (PDOException $e) {
die('nested failed');
}
echo '<table border="0" cellpadding="0" cellspacing="0" width="200">';
do {
echo '<tr><td width="100">'.$row_nested['size'].'</td><td width="100">'.$row_nested['amount'].'</td></tr>';
} while ($row_nested = $nested->fetch(PDO::FETCH_ASSOC));
echo '</table>';
echo '</td></tr>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
</table>
while($b = mysql_fetch_array($a)) {
echo "id event </br>".$b[id_event] ."</br>";
echo "id user </br>".$b[id_user] ."</br>";
it's output
3 - 32
3 - 36
4 - 32
4 - 36
I want make it to display all users under one event id, like that
3 - 32, 36
4 - 32, 36
I tried like that
while($b = mysql_fetch_array($a)) {if ($b['id_event'] != $current_event) {
$current_event = $b['id_event'];
echo '<br>' . $b['id_event'] . ' - ' . $b['id_user'];
} else { echo ', ';}}
but it selected only one user for one event id
3 - 32,
4 - 32,
You can map the results to an intermediate list for processing.
Check out the PHPFiddle: http://phpfiddle.org/main/code/evx-g61
$event_list = array();
while ($b = mysql_fetch_array($a)) {
if (!array_key_exists($b["id_event"], $event_list)) {
$event_list[$b["id_event"]] = array();
}
$event_list[$b["id_event"]][] = $b["id_user"];
}
foreach ($event_list as $event => $users) {
echo "<span>$event - " . join(", ", $users) . "</span><br />";
}
It work's fine but I can't display data for each $users when I'm using join commend
foreach ($event_list as $event => $users) {
echo "<span>$event - " . join( $users,"some data") . "</span><br />";}
it's echo
3 - 36a32
4 - 36a32
and I was expecting
3 - 36a32a
4 - 36a32a