I am trying to take this style of code and generate based on how many machines are returned from the database.
I have this:
<table style="width: 100%; height:85%;table-layout:fixed;text-align:center;">
<tr>
<td><?php echo $array[0]; ?> <span class="blue">#1</span><br>
sets <span class="blue">1</span> reps <span class="blue">50</span><br>
weight <span class="blue">25</span></td>
<td><?php echo $array[1]; ?> <span class="blue">#2</span><br>
sets <span class="blue">1</span> reps <span class="blue">100</span><br>
weight <span class="blue">40</span></td>
</tr>
<tr>
<td><?php echo $array[2]; ?> <span class="blue">#3</span><br>
sets <span class="blue">2</span> reps <span class="blue">25</span><br>
weight <span class="blue">20</span></td>
<td><?php echo $array[3]; ?> <span class="blue">#4</span><br>
sets <span class="blue">3</span> reps <span class="blue">25</span><br>
weight <span class="blue">30</span></td>
</tr>
</table>
Here is the database code to retrieve the machines from the database:
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();
while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
$array[] = $row['machine_name'];
}
I want the code to detect how many machines are in the database that aren't cardio machines and generate the number of table rows accordingly.
Here is a visual representation:
Since you are loading all of your results into an array you can use array_chunk to break the array into rows and then output accordingly.
$array = array_chunk($array, 4);
echo '<table style="width: 100%; height:85%;table-layout:fixed;text-align:center;">';
foreach($array as $row){
echo "<tr>";
foreach($row as $cell){
// echo out your tds for format each cell here.
}
echo "</tr>";
}
echo '</table>';
Updated for hard-coded machine attributes (not really a good idea)
$machine_atts = array(
'bicep curl' => array( 'sets' => 1, 'reps' => 50, 'weight' => 25 ),
'cable chest press' => array( 'sets' => 1, 'reps' => 100, 'weight' => 40 ),
'lat pulldown' => array( 'sets' => 2, 'reps' => 25, 'weight' => 20 ),
'tricep extension' => array( 'sets' => 3, 'reps' => 25, 'weight' => 30 ),
);
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();
$i=0;
while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
$i++;
$sets = $machine_atts[$row['machine_name']]['sets'];
$reps = $machine_atts[$row['machine_name']]['reps'];
$weight = $machine_atts[$row['machine_name']]['weight'];
$array[] = '<td>'.$row['machine_name'].'> <span class="blue">'.$i.'</span><br>sets <span class="blue">'.$sets.'</span> reps <span class="blue">'.$reps.'</span><br>weight <span class="blue">'.$weight.'</span></td>';
}
echo '<table style="width: 100%; height:85%;table-layout:fixed;text-align:center;">';
foreach ( array_chunk( $array, 2 ) as $chunk )
echo '<tr>' . implode('', $chunk ) . '</tr>';
echo '</table>';
Original Answer
Assuming the number of sets, number of reps, and weight are in the results set of the query:
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();
$i=0;
while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
$i++;
$array[] = '<td>'.$row['machine_name'].'> <span class="blue">'.$i.'</span><br>sets <span class="blue">'.$row['sets'].'</span> reps <span class="blue">'.$row['reps'].'</span><br>weight <span class="blue">'.$row['weight'].'</span></td>';
}
echo '<table style="width: 100%; height:85%;table-layout:fixed;text-align:center;">';
echo '<tr>' . implode('</tr><tr>', array_chunk( $array, 2 ) ) . '</tr>';
echo '</table>';
<?php
for ($x=0; $x<sizeOf($array); $x++) {
echo '<tr><td>Array Data Here</td></tr>';
}
?>
Related
In the following codes, its coming numbers 1, 2, 3, 4, 5 .....and so on but i need that number in 5, 4, 3, 2,1 like that
<?php
//$events = $db->select("select * from main_menu where mm_menu='4' and mm_status='1' and mm_project='1' order by mm_order asc limit 0,10");
$events = $db->select("select * from main_menu where mm_menu='4' and mm_status='1' and mm_project='1' order by mm_id desc");
if (count($events) > 0) {
$i = 1;
foreach ($events as $event_info) {
$clsIn = ($i==1) ? "in" : "";
$clsOut = ($i==1) ? "" : "collapsed";
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $event_info['mm_title'];?></td>
<td><?php echo html_entity_decode($event_info['mm_content']);?></td>
</tr>
<?php
$i++;
}
}?>
If you want to count down, set $i to the total number of events, and then decrement it:
First:
$i = count($events);
and then at the end of the loop:
$i--;
I have a total of 8 results/users in my MYSQL table 'users'.
I want to display 6 results/user profile images per row like so:
1st Result. 2nd Result. 3rd Result. 4th Result. 5th Result. 6th Result
7th Result. 8th Result. No More Results.....
It is a requirement for each row to be complete with a minimum of 6 results/profile images. Where there is not enough results/profile images to complete a row, then I am trying to fill in the space with a template profile image 'advertise your profile here'.
The advertise here template image is stored in the following directory:
<div><img src="data/profile/0/main/advert.jpg" alt="Profile" height="100%" width="100%"></div>';
Giving the desired result:
1st Result. 2nd Result. 3rd Result. 4th Result. 5th Result. 6th Result
7th Result. 8th Result. 9 Ad Here. 10 Ad Here. 11 Ad Here. 12 Ad Here.
Here is my code I have currently with compliments to user #MegaColorBoy for helping me with the code so far.
However, the code is still not giving the desired result. Please can someone help improve amend the code to get it to give me the result i require. Thank you.
code:
<?php $sql = "SELECT * FROM users WHERE status = 'active' AND usertype = 'advertiser'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
$limit = 6;
$chunks = array_chunk($result, $limit);
foreach($chunks as $chunk){
echo '<div id="category_case_holder">';
foreach($chunk as $chunkItem){
echo '<div id="prime"><img src="data/profile/'.htmlspecialchars($chunkItem['user_id']).'/main/profile.jpg" alt="Profile" height="100%" width="100%"></div>';
}
echo '</div>';
} ?>
You can easily achieve that using the array_chunk() method.
Example:
//set it to whatever limit you want.
$limit = 6;
// this will divide the array into x number of chunks based on y limit.
$chunks = array_chunk($result, limit);
foreach($chunks as $chunk){
echo '<div>';
foreach($chunk as $chunkItem){
// your stuff here
}
echo '</div>';
}
Refer to PHP's official documentation: https://www.php.net/manual/en/function.array-chunk.php
If I understand your question, I think you should try this:
<div id="category_case_holder">
<table>
<tr>
<?php
$sql = "SELECT * FROM users WHERE status = 'active' AND usertype = 'advertiser'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
$resultNumber = count($result);
for ($i = 1; $i <= $resultNumber; $i++) {
echo "<td>";
$key = $i - 1;
if (isset($result[$key])) {
$filename = "data/profile/$i/main/profile.jpg";
if (file_exists($filename)) {
echo '<div id="prime"><img src="data/profile/'.htmlspecialchars($result[$key]['user_id']).'/main/profile.jpg" alt="Profile" height="100%" width="100%"></div>';
} else {
echo '<div id="prime"><img src="data/profile/0/main/profile.jpg" alt="Profile" height="100%" width="100%"></div>';
}
} else {
echo '<div id="prime"><img src="data/profile/0/main/advert.jpg" alt="Profile" height="100%" width="100%"></div>';
}
echo "</td>";
if (($i % 6) == 0 && $i <= $resultNumber) {
echo "</tr>";
echo "<tr>";
}
}
?>
</tr>
</div>
The following is wholly untested and perhaps wide of the mark having not seen the data nor had an answer regarding the profile image but the general aim was to break the results array into little bits - array_chunk is ideal for this.
<div id="category_case_holder">
<?php
$sql = "SELECT * FROM `users` WHERE `status` = 'active' AND `usertype` = 'advertiser'";
$result = $conn->query( $sql )->fetch_all( MYSQLI_ASSOC );
# a placeholder in the path will be substituted later using sprintf or printf
$filepath = 'data/profile/%s/main/profile.jpg';
if( !empty( $result ) ){
# split the recordset array into chunks - 6 records long.
# Each chunk will be a row from recordset.
$chunks=array_chunk( $result, 6 );
foreach( $chunks as $chunk ){
echo '<div>';
foreach( $chunk as $i => $rs ){
$filename=file_exists( sprintf( $filepath, $i ) ) ? sprintf( $filepath, $rs['user_id'] ) : sprintf( $filepath, '0' );
# ID attributes MUST be unique.
# substitue placeholders for values from this row data
printf('
<div class="prime">
<a href="profile.php?id=%s">
<img src="%s" alt="Profile" height="100%" width="100%">
</a>
</div>',
htmlspecialchars( $rs['user_id'] ),
$filename
);
}
echo '</div>';
}
}else{
echo '<div id="prime"><img src="data/profile/0/main/advert.jpg" alt="Profile" height="100%" width="100%"></div>';
}
?>
</div>
Let's say i have the following array:
$array = [
['time_spent' => 10, 'rate' => 150],
['time_spent' => 20, 'rate' => 100]
];
I want the table to look like the following:
It has 2 rows and 4 columns (Time Spent, Rate, Total, Grand Total):
The first row will be:
10 | 150 | 10 x 150 = 1500 | 3500
and the second row:
20 | 100 | 10 x 200 = 2000
(3500 is the sum of the total of both records)
Assuming you you wanted to output an HTML table, something like this would work.
$array= [
["time_spent"=> 10, "rate"=> 150],
["time_spent"=> 20, "rate"=> 100]
];
$html = [];
$sum = 0;
foreach ($array as $i => $row) {
$product = $row['rate'] * $row['time_spent'];
$line = "<tr><td>{$row['time_spent']}</td><td>{$row['rate]'}</td>";
$line .= "<td>{$row['time_spent']} x {$row['rate']} = {$product}</td>";
if ($i !== 0) {
$line .= '</tr>';
}
$html[] = $line;
$sum += $product;
}
$rowCount = count($html);
$html[0] .= "<td rowspan='{$rowCount}'>{$sum}</td></tr>";
echo '<table>' . implode('', $html) . '</table>';
EDIT: Changed code to reflect the change in input.
Note that there would be better ways to simply calculate total sum. This method generates the desired display along with the sum with a single loop through the data.
Using html template strings with s/printf() does a great job of keeping clean, readable code with separation between processing and markup.
I am purposely making this script verbose. The advantage in this script is readability and maintainability.
It is an unusual requirement to have the grand total in the right column of the table instead of the final row of the table. If you desired the total to be in the final row, then the code would be easier to write and read (for humans).
In my demo, click on the eye icon in the upper right of the output box to see the html rendered version of the result.
Code: (Demo)
$array = [
['time_spent' => 10, 'rate' => 150],
['time_spent' => 20, 'rate' => 100]
];
$tableMarkup = <<<'HTML'
<table>
%s
%s
</table>
HTML;
$headerRowMarkup = <<<'HTML'
<tr>
<th>Time Spent</th>
<th>Rate</th>
<th>Total</th>
<th>Grand Total</th>
</tr>
HTML;
$firstRowMarkup = <<<'HTML'
<tr>
<td>%1$d</td>
<td>%2$d</td>
<td>%1$d x %2$d = %3$d</td>
<td rowspan="%4$d">%5$d</td>
</tr>
HTML;
$subsequentRowMarkup = <<<'HTML'
<tr>
<td>%1$d</td>
<td>%2$d</td>
<td>%1$d x %2$d = %3$d</td>
</tr>
HTML;
$rowsMarkup = [];
$count = count($array);
if ($count) {
$grandTotal = array_reduce(
$array,
function ($carry, $row) {
$carry += $row['rate'] * $row['time_spent'];
return $carry;
},
0
);
$row = array_shift($array);
$rowsMarkup[] = sprintf(
$firstRowMarkup, // template string
$row['time_spent'], // %1$d
$row['rate'], // %2$d
$row['time_spent'] * $row['rate'], // %3$d
$count, // %4$d
$grandTotal // %5$d
);
}
foreach ($array as $row) {
$rowsMarkup[] = sprintf(
$subsequentRowMarkup,
$row['time_spent'],
$row['rate'],
$row['time_spent'] * $row['rate']
);
}
if ($rowsMarkup) {
printf(
$tableMarkup,
$headerRowMarkup,
implode("\n", $rowsMarkup)
);
}
You need to calculate the grand total before you start printing the table. Then you can show it on the first row of the table.
$grand_total = 0;
foreach ($array as $item) {
$grand_total += $item['rate'] * $item['time_spent'];
}
echo "<table>";
foreach ($array as $i => $item) {
$total = $row['time_spent'] * $row['rate'];
echo "<tr><td>{$row['time_spent']}</td><td>{$row['rate']}</td>";
if ($i == 0) { // first row, show grand total
echo "<td>$total</td><td>$grand_total</td>";
} else {
echo "<td colspan='2'>$total</td>";
}
echo "</tr>";
}
echo "</table>";
I've been trying for a while but still, I'm stuck here. Actually I need to get rank from average values. Here my result
Average Rank
39 39 rank is 1
32 32 rank is 1
51 51 rank is 1
57 57 rank is 1
what I really need is
Average Rank
39 3
32 4
51 2
57 1
I've tried several method, but nothing seem to be works. Btw Here's my code
<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?>
<?php
$array = array($avg);
$i=1;
foreach($array as $key=>$value)
{
$max = max($array);
echo "\n".$max." rank is ". $i."\n";
$keys = array_search($max, $array);
unset($array[$keys]);
if(sizeof($array) >0)
if(!in_array($max,$array))
$i++;
}
And Here's the full Code
<?php $nama_mapel=$ux['nama_mapel'];
$an = mysql_fetch_array(mysql_query("SELECT*FROM mapel where kode_kelas='$kode_kelas' and nama_mapel='$nama_mapel'"))?>
<text style="display:none;"><?php if($NILAI_AKHIR!=0){$NILAI_AKHIR4=substr($NILAI_AKHIR/100*4,0,4); echo $NILAI_AKHIR4;} ?></text>
<tr>
<td width="5%" class="ki1234" height="auto" valign="center" align="center"><?php echo $no++ ;?></td>
<td width="40%" class="ki1234" height="auto" valign="center" align="left"> <?php echo $mmm['nama'];?></td>
<td width="10%" class="ki1234" height="auto" valign="center" align="center"><?php echo $nis; ?></td>
<?php
$mapelz=mysql_query("SELECT*FROM mapel where kode_kelas='$kode_kelas' and id_tp='$id_tp'");
$arrg=[];
while($uxe = mysql_fetch_array($mapelz)){
$id_mapel=$uxe['id_mapel'];
//awal nilai akhir//
$dren = mysql_query("SELECT*FROM nilai_siswa,data_siswa,penilaian_judul where nilai_siswa.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa.nis=data_siswa.nis and nilai_siswa.nis=$nis and penilaian_judul.id_mapel=$id_mapel and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp' order by data_siswa.id_siswa asc"); $jm=mysql_num_rows($dren); $jumlah_tugas=$jm;
if($jm==0){$jumlah="1";} else {$jumlah=$jm; };
$queryj=mysql_query("SELECT sum(n3_100) as rn3_100 FROM nilai_siswa,penilaian_judul where nilai_siswa.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa.nis=$nis and penilaian_judul.id_mapel=$id_mapel and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp'");
while($hasil=mysql_fetch_array($queryj))
{$rn3_100=substr($hasil['rn3_100']/$jumlah,0,5); $RATA_TUGAS=$rn3_100;}
$dren = mysql_query("SELECT*FROM nilai_siswa2,data_siswa,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=data_siswa.nis and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=2 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp' order by data_siswa.id_siswa asc"); $jm=mysql_num_rows($dren); $jumlah_uh=$jm;
if($jm==0){$jumlah="1";} else {$jumlah=$jm;};
$queryj=mysql_query("SELECT sum(n_100) as rn_100 FROM nilai_siswa2,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=2 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp'");
while($hasil=mysql_fetch_array($queryj))
{$rn_100=substr($hasil['rn_100']/$jumlah,0,5); $RATA_UH= $rn_100;}
$dren = mysql_query("SELECT*FROM nilai_siswa2,data_siswa,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=data_siswa.nis and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=3 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp' order by data_siswa.id_siswa asc"); $jm=mysql_num_rows($dren); $jumlah_uts=$jm;
if($jm==0){$jumlah="1";} else {$jumlah=$jm;};
$queryj=mysql_query("SELECT sum(n_100) as rn_100 FROM nilai_siswa2,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=3 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp'");
while($hasil=mysql_fetch_array($queryj))
{$rn_100=substr($hasil['rn_100']/$jumlah,0,5); $RATA_UTS= $rn_100;}
$dren = mysql_query("SELECT*FROM nilai_siswa2,data_siswa,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=data_siswa.nis and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=4 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp' order by data_siswa.id_siswa asc"); $jm=mysql_num_rows($dren); $jumlah_us=$jm;
if($jm==0){$jumlah="1";} else {$jumlah=$jm;};
$queryj=mysql_query("SELECT sum(n_100) as rn_100 FROM nilai_siswa2,penilaian_judul where nilai_siswa2.id_penilaian_judul=penilaian_judul.id_penilaian_judul and nilai_siswa2.nis=$nis and penilaian_judul.id_mapel=$id_mapel and nilai_siswa2.jenis=4 and penilaian_judul.id_semester='$id_semester' and penilaian_judul.id_tp='$id_tp'");
while($hasil=mysql_fetch_array($queryj))
{$rn_100=substr($hasil['rn_100']/$jumlah,0,5); $RATA_US= $rn_100;}
if(!isset($RATA_TUGAS)){$RATA_TUGAS2=0;}else{$RATA_TUGAS2=$RATA_TUGAS;};
if(!isset($RATA_UH)){$RATA_UH2=0;}else{$RATA_UH2=$RATA_UH;};
if(!isset($RATA_UTS)){$RATA_UTS2=0;}else{$RATA_UTS2=$RATA_UTS;};
if(!isset($RATA_US)){$RATA_US2=0;}else{$RATA_US2=$RATA_US;};
$jumlahc=($persen['tugas']*$RATA_TUGAS2)/100+($persen['uh']*$RATA_UH2)/100+($persen['uts']*$RATA_UTS2)/100+($persen['us']*$RATA_US2)/100;
if($jumlah_tugas!=0){$k=1;} else {$k=0;};
if($jumlah_uh!=0){$l=1;} else {$l=0;};
if($jumlah_uts!=0){$m=1;} else {$m=0;};
if($jumlah_us!=0){$n=1;} else {$n=0;};
$JUMLAH_PERSEN1=($persen['tugas']*$k)+($persen['uh']*$l)+($persen['uts']*$m)+($persen['us']*$n);
if($JUMLAH_PERSEN1==0){$JUMLAH_PERSEN=1;}else{$JUMLAH_PERSEN=$JUMLAH_PERSEN1;};
$NILAI_AKHIRg=substr(($jumlahc/$JUMLAH_PERSEN)*100,0,5);
$nile= $NILAI_AKHIRg;
$arrg[] = $NILAI_AKHIRg;} ?>
<?php $p = mysql_fetch_array(mysql_query("SELECT * FROM peringkat WHERE kode_kelas='$kode_kelas' and nis='$nis'and id_tp='$id_tp'")); ?>
<text style="display:none;"> <?php $sumc = 0; $output = ""; while($element = array_shift($arrg)){$sumc += $element; $output .= $element; if(sizeof($arrg) > 0){ $output .= " + ";}} echo $output . PHP_EOL;?></text>
<td width="15%" class="ki1234" height="auto" valign="center" align="center"><?php echo $sumc;?></td>
<text style="display:none;"><?php $result=mysql_query("SELECT count(*) as total FROM mapel WHERE kode_kelas='$kode_kelas' and kel!=3"); $data=mysql_fetch_assoc($result); echo $data['total'];?></text>
<td width="15%" class="ki1234" height="auto" valign="center" align="center"><?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?></td>
<td width="15%" class="ki1234" height="auto" valign="center" align="center"><?php
$array = array($avg);
$i=1;
foreach($array as $key=>$value)
{
$max = max($array);
echo "\n".$max." rank is ". $i."\n";
$keys = array_search($max, $array);
unset($array[$keys]);
if(sizeof($array) >0)
if(!in_array($max,$array))
$i++;
}
?></td>
</tr>
<?php }?>
Need Your help.. Anyone..?!
<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?>
<?php
$array = array($avg); // useless
$i=1;
foreach($array as $key=>$value) // also useless, you never use these variables, and since $array contains only one entry, there is no need to foreach it
{
$max = max($array);
echo "\n".$max." rank is ". $i."\n";
$keys = array_search($max, $array);
unset($array[$keys]);
if(sizeof($array) >0)
if(!in_array($max,$array))
$i++;
}
Let's clean that up :
<?php $avg = ($sumc)/($data['total']); echo number_format((float)$avg, 2, ',', ''); ?>
<?php
$max = $avg; // That's actually what you were doing. Cleaning the code makes it obvious, that's all
echo "\n".$max." rank is ". $i."\n";
$keys = array_search($max, $array);
unset($array[$keys]);
if(sizeof($array) >0)
if(!in_array($max,$array))
$i++;
}
The code still has errors, but the more we correct, the more its design flaws appear, and the less it's therefore correctable.
You should, in my opinion, look at that code, figure a way to put all the values you want to have in $array in it so that then you can compute the datas you need.
From what you've posted seems the problem is how to sort the average values descending.
With this in mind you know that if you're calculating the average on the go, you have to go throuh the entire array first so here's some snippet to help you:
// Random values I want to calculate the average
$values = [
1 => [15, 25, 35],
2 => [45, 55, 65],
3 => [75, 85, 95],
4 => [105, 115, 125]
];
$avgs = array();
foreach ($values as $key => $value) {
$avgs[$key] = array_sum($value) / count($value); // calculate average for each key on the array
}
print_r($avgs);
// Will print:
// Array
// (
// [1] => 25
// [2] => 55
// [3] => 85
// [4] => 115
//)
arsort($avgs); // sort the array in descending order
print_r($avgs);
// Will print:
//Array
//(
// [4] => 115
// [3] => 85
// [2] => 55
// [1] => 25
//)
So there if have your avg array sorted, therefore you have your "rank".
ps. The keys 1, 2, 3, 4 are just random values, you could have anything there.
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I have a mysql query that returns an array of rows. How would i populate my html table using php vertically? there is no limit to how many columns i my HTML table allowed.
My MYSQL query returns about 40 columns per row.
MYSQL row1 => 10|11|12|13|14|15|16|17|18|19
row2 => 20|21|22|23|24|25|26|27|28|29
row3 => 30|31|32|33|34|35|36|37|38|39
HTML output should look like this
10 | 20 | 30
11 | 21 | 31
12 | 22 | 32
13 | 23 | 33
14 | 24 | 34
15 | 25 | 35
16 | 26 | 36
17 | 27 | 37
18 | 28 | 38
19 | 29 | 39
this is my code, and it's displaying nothing.
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
$c = 1;
while ($c <= $numrows)
{
$values['col_'.$c] = array();
$c++;
}
$r = 1;
while ($row = $_db->fetch_array($result))
{
$values['col_'.$c][$r] = $row;
$r++;
}
echo "<table border='1'>";
for ($r = 1; $r <= $numrows; $r++)
{
echo "<tr>";
for ($c = 1; $c <= sizeof($values['col_1']); $c++)
{
echo "<td>".$values['col_'.$c][$r]."</td>";
}
echo "</tr>" ;
}
echo "</table>" ;
Any idea what i'm doing wrong? or how to make it simpler? (i think there are too many while loops)
I think what you want is creating the php array from the mysql query, transposing the array (like you would transpose a matrix) and display it.
Transposing an array is a solved problem (transposing multidimentional arrays in php)
For the rest, it is pretty simple ... here is my code:
$res = mysqli_query(...);
$anarr = array();
while ($row = mysqli_fetch_array($res,$result_type=MYSQLI_ASSOC)){
$anarr[] = $row;
}
// here is the transpose part
array_unshift($anarr, null);
$transposedarr = call_user_func_array('array_map', $anarr);
// end of the transpose part
echo '<table>';
foreach ($transposedarr as $r){
echo '<tr>';
foreach ($r as $c){
echo '<td>'.$c.'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
You are assigning only one row in your while loop. Change that with below code:
while ($row = $_db->fetch_assoc($result))
{
$values['col_'.$c][$r] = $row;
$c++;
$r++;
}
Here you are assigning the value to $value['col_1'][$r] and not increasing the value of $c. So at the end it override the values.
You can simplify the problem by just saying
$values[$rowIndex] = $columnArray
So in this case
$values[0] = array( 10, 20, 30 );
$values[1] = array( 11, 21, 31 );
And then loop across each array
echo "<table border='1'>";
foreach( $values as $row )
{
echo "<tr>";
foreach( $row as $columnValue )
{
echo ..whatever..
}
echo "<tr>";
}
echo "</table>" ;
Or something along these lines. I just basically psuedo coded this though, I have no access to php interpreter right now.
//while and foreach loop can do this
<?php
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
//check here
if($numrows>0)
{
//1 row
$r = 1;
//column
$c=0;
while ($row = $_db->fetch_assoc($result))
{
//value row column
$values[$r][$c] = $row;
//column == 3
if($c==2)
{
//increase row
$r++;
//reset column
$c = 0;
}else{
$c++;
}
}
echo "<table border='1'>";
//display row and columns
foreach($values as $row)
{
echo "<tr>";
echo "<td>".$values[0]."</td>";
echo "<td>".$values[1]."</td>";
echo "<td>".$values[2]."</td>";
echo "</tr>" ;
}
echo "</table>" ;
}
You can do everything in a single loop. Additionally, at least for your purposes in this example, I don't understand why you're putting everything in an array and then echo, instead of echoing it directly.
e.g. (tested):
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
echo "<table border='1'>";
$tab = array();
while ($row = $result->fetch_row())
{
$tab[] = $row;
}
for( $i = 0, $l = count($tab[$i]); $i < $l; $i++){
echo "<tr>";
for( $j = 0, $m = count($tab); $j < $m; $j++){
echo "<td>".$tab[$j][$i]."</td>";
}
echo "</tr>" ;
}
echo "</table>";
UPDATE: I completely changed my code. I didn't get initially what you needed.
Does this code help you?
This is how I would tackle it. The most difficult part is preparing the structure in which you prepare the table. It uses the following syntax: $somearray[] = $x, which appends $x to array $somearray. implode() concats an array together with a string you define. Last but not least, you were using mysql_fetch_assoc, which returns an associative array (Array( [column1] => "val1" ); etc). You want a numbered array instead for these kind of operations. This can be accomplished with mysql_fetch_array with a second argument of MYSQL_NUM.
$arrayOfRows = Array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$firstrun = true;
while( $row = $_db->fetch_array($result, MYSQL_NUM) ) {
#Setup structure on first run
if( $firstrun ) {
$firstrun = false;
for( $i = 0; $i < count( $row ); $i++ ) {
$arrayOfRows[$i] = Array();
}
}
#Each field in this mysql row needs to be in a different html row
foreach( $row as $k => $v ) {
$arrayOfRows[$k][] = $v;
}
}
#Now simply print it
echo '<table>';
foreach( $arrayOfRows as $k => $row ) {
echo '<tr>';
echo '<td>' . implode( '</td><td>', $row ) . '</td>';
echo '</tr>';
}
echo '</table>';
<?php
$arr = array(array(1,2,3,4,5,6,7,8,9), array(10,11 etc . . .
for($i = 0; $i < 9; ++ $i){
for($x = 0; $x < $num_rows; ++ $x){
echo $arr[$x][$i];
}
echo '<br/>';
}
?>
U may replace 9 with number of columns in tables
I not shure what it this code correct (can't test now), but i think it can help you
Sorry if i do something wrong, i just try to help