I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}
Related
I have an API that's showing almost 100 trades that I want to limit to just 10. I've tried
if($bitcointrades == 10) break
but that didn't work. Do I run a for loop after I pull the data? Should I break up the functions into two parts as opposed to using elseif to present $trades? Here's what I'm working with:
<?php
require_once('bitcoin.class.php');
$data = new Bitcoin();
$type = $_GET['type'];
$currency = $_GET['currency'];
if($type == 'ticker') {
$bitcoinlive = $data->getPrice($currency);
echo '<h2>1 Bitcoin is currently worth <span class="bitvalue">' .
number_format((float)$bitcoinlive['last'], 2) . ' <span class="upper">'
. $currency . '</span></span></h2>';
echo ' <p><span><i class="icon-arrow-up-circle"></i> High: ' .
number_format((float)$bitcoinlive['high'], 2) . '</span> <span><i
class="icon-arrow-down-circle"></i> Low: ' .
number_format((float)$bitcoinlive['low'], 2) . '</span>';
} elseif($type == 'trades') {
$bitcointrades = $data->getTrades($currency);
foreach($bitcointrades as $trade) {
if($trade['type'] == 'buy') {
$ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy
Order</span>';
} else {
$ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell
Order</span>';
}
echo' <tr> <th scope="row">' . $ttype . '</th> <td>' . $trade['price']
. ' <span class="upper">' . $currency . '</span></td> <td>' .
$trade['amount'] . '</td> <td>' . $data->timeAgo($trade['date']) .
'</td> </tr>';
}
}
It's normal if($bitcointrades == 10) break isn't going to work.
$bitcointrades should be an array with trades which you define as $trade.
You need to use an iterator i like in the example below:
<?php
$i = 0;
foreach($bitcointrades as $trade) {
if($i==10)
break;
// your logic here
$i++;
}
You can finish a foreach execution using break so you can use a cnt and break
$my_cnt = 0;
foreach($bitcointrades as $trade) {
if ($my_cnt >= 10) {
break;
}
if($trade['type'] == 'buy') {
$ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy
Order</span>';
} else {
$ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell
Order</span>';
}
$my_cnt++;
}
Do Like this way
$i = 0;
foreach ($bitcointrades as $trade) {
if ($trade['type'] == 'buy') {
$ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy Order</span>';
} else {
$ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell Order</span>';
}
echo ' <tr> <th scope="row">' . $ttype . '</th> <td>' . $trade['price']
. ' <span class="upper">' . $currency . '</span></td> <td>' .
$trade['amount'] . '</td> <td>' . $data->timeAgo($trade['date']) .
'</td> </tr>';
$i++;
if ($i == 10) {
break;
}
}
The following code is displaying product name in one row and quantity,price and subtotal in new row, how to get all these on same row. Output screenshot as been attached below.
code output
<table class="table table-striped table-condensed">
<tbody>
<?php
$r = 1;
$tax_summary = array();
foreach ($rows as $row) {
if (isset($tax_summary[$row->tax_code])) {
$tax_summary[$row->tax_code]['items'] += $row->quantity;
$tax_summary[$row->tax_code]['tax'] += $row->item_tax;
$tax_summary[$row->tax_code]['amt'] += ($row->quantity * $row->net_unit_price) - $row->item_discount;
} else {
$tax_summary[$row->tax_code]['items'] = $row->quantity;
$tax_summary[$row->tax_code]['tax'] = $row->item_tax;
$tax_summary[$row->tax_code]['amt'] = ($row->quantity * $row->net_unit_price) - $row->item_discount;
$tax_summary[$row->tax_code]['name'] = $row->tax_name;
$tax_summary[$row->tax_code]['code'] = $row->tax_code;
$tax_summary[$row->tax_code]['rate'] = $row->tax_rate;
}
echo '<tr><td colspan="2">#' . $r . ': ' . product_name($row->product_name) . ($row->variant ? ' (' . $row->variant . ')' : '') . '<span class="pull-right">' . $row->tax_code . '</span></td></tr>';
echo '<tr><td>' . $this->sma->formatNumber($row->quantity) . ' x ';
if ($row->item_discount != 0) {
echo '<del>' . $this->sma->formatMoney($row->net_unit_price + ($row->item_discount / $row->quantity) + ($row->item_tax / $row->quantity)) . '</del> ';
}
echo $this->sma->formatMoney($row->net_unit_price + ($row->item_tax / $row->quantity)) . '</td><td class="text-right">' . $this->sma->formatMoney($row->subtotal) . '</td></tr>';
$r++;
}
?>
</tbody>
<tfoot>
<tr>
Try below, but probabbly the formatting will be broken:
<table class="table table-striped table-condensed">
<tbody>
<?php
$r = 1;
$tax_summary = array();
foreach ($rows as $row) {
if (isset($tax_summary[$row->tax_code])) {
$tax_summary[$row->tax_code]['items'] += $row->quantity;
$tax_summary[$row->tax_code]['tax'] += $row->item_tax;
$tax_summary[$row->tax_code]['amt'] += ($row->quantity * $row->net_unit_price) - $row->item_discount;
} else {
$tax_summary[$row->tax_code]['items'] = $row->quantity;
$tax_summary[$row->tax_code]['tax'] = $row->item_tax;
$tax_summary[$row->tax_code]['amt'] = ($row->quantity * $row->net_unit_price) - $row->item_discount;
$tax_summary[$row->tax_code]['name'] = $row->tax_name;
$tax_summary[$row->tax_code]['code'] = $row->tax_code;
$tax_summary[$row->tax_code]['rate'] = $row->tax_rate;
}
echo '<tr><td colspan="2">#' . $r . ': ' . product_name($row->product_name) . ($row->variant ? ' (' . $row->variant . ')' : '') . '<span class="pull-right">' . $row->tax_code . '</span>';
echo '' . $this->sma->formatNumber($row->quantity) . ' x ';
if ($row->item_discount != 0) {
echo '<del>' . $this->sma->formatMoney($row->net_unit_price + ($row->item_discount / $row->quantity) + ($row->item_tax / $row->quantity)) . '</del> ';
}
echo $this->sma->formatMoney($row->net_unit_price + ($row->item_tax / $row->quantity)) . '' . $this->sma->formatMoney($row->subtotal) . '</td></tr>';
$r++;
}
?>
</tbody>
I'm trying to set a checkbox as checked in php based on an hour fields from a comma separated value string. It works well for 1-23 but for some reason hour 0 always displays as checked:
<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
The problem is straightforward; look at the outer loop:
for ($hour = 0; $hour <= 23; $hour++) {
Consider only the first iteration, so $hour is int(0). Further in the code:
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
Pay close attention to the loop condition:
$h <= count($myhours)
Consider the last iteration of that loop, so $h equals the size of your array.
if ((int)$hour == (int)$myhours[$h]) {
At this point $myhours[$h] is undefined because the array index is out of bounds (and a notice would have been emitted) and so (int)$myhours[$h] becomes (int)null which is int(0). The comparison is therefore always true when $hour has the value of int(0).
The solution is to change the loop condition to:
$h < count($myhours)
Not exactly and answer, but your code could be reduced to this:
$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';
}
No need for a second loop and more variables here. Also be aware to not output values from $_REQUEST directly without any check.
Demo
Try before buy
Problem solved. It was actually the count($myhours) that was causing the problem. Basically even with an empty string it still returns an array with 1 element. Changed to check if count($myhours) > 1 and everything is working as expected:
<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 1) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
While making a photo gallery I encountered a problem. With every photo I try to show how many comments it has, however if a photo has 0 comments it will give me an 'undefined offset' error. I have no idea what I am doing wrong because it does show that there are 0 comments.
This is the code of what is relevant to the problem:
(The problem occurres in the line: if($reacties[$i]==0){)
if((isset($_GET['vanafFoto'])) AND (intval($_GET['vanafFoto']>=0)) AND (intval($_GET['vanafFoto'] < $countFotos))){
$begin = intval($_GET['vanafFoto']);
if(($begin + $aantalFotos) <= $countFotos){
$eind = ($begin + $aantalFotos);
} // end if
else {
$eind = $countFotos;
} // end else
} // end if
else {
$begin = 0;
$eind = $aantalFotos;
} // end else
$countFotos = count($fotoArray);
// path naar echte foto
} // end else
echo "<table border='0' cellpadding='0' cellspacing='2'><tr><td ><b>" . $pathspatie . "</b> <small>(" . $count . ")</small>
<br><br><center><small>Pictures " . ($begin + 1) . " - " . $eind . "</small></center></td></tr></table>";
if(($begin - $aantalFotos) >= 0){
$navigation = "<a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin - $aantalFotos) . "'><</a> " . $navigation;
} // end if
if(($begin + $aantalFotos) < $count){
$navigation .= " <a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin + $aantalFotos) . "'>></a>";
} // end if
echo $navigation . "<br><br>";
echo "</td></tr><tr>";
$fotonr = 1;
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){ // error occurres here.
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
} // end for
If anyone can see what the problem is it would be great!
I did not understand you exact goal but maybe it is better to write one more check:
if(!isset($reacties[$i]) || $reacties[$i]==0){
echo "0";
}
I have a script which retrieves all rows of data within a sales list (npc_sales_list) but what I am trying to do is set up a drop down menu which filters the results oand I don't know where to start as I haven't done any php in while.
The main filters I am trying to do are to see the previous month's sales only (npc_entry_date) and the sales type (npc_usertype). If someone could point me in the right direction or show me some resource links that would be great.
Im not fussed whether the filter is automatic or if you need to hit a submit button. Any suggestions welcome...
<?php
require_once ('./includes/config.inc.php');
$page_title = 'Page title';
include ('./includes/header.html');
if (!isset($_SESSION['admin_sp_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean();
header("Location: $url");
exit();
}
require_once ('database.php');
$display = 500;
if (isset($_GET['np'])) {
$num_pages = $_GET['np'];
} else {
$query = "SELECT COUNT(*) FROM npc_sales_list ORDER BY npc_entry_date DESC";
$result = #mysql_query ($query);
$row = mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) {
$num_pages = ceil ($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=lna";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'fna':
$order_by = 'sp_firstname ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'sp_firstname DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'lna':
$order_by = 'sp_surname ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'sp_surname DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
default:
$order_by = 'npc_entry_date DESC';
break;
}
// $sort will be appended to the pagination links.
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'npc_entry_date DESC';
$sort = 'drd';
}
$query = "SELECT us.sp_firstname , us.sp_surname , us.sp_amb_club_no , us.sp_position_title , us.sp_dealer_name ,
us.sp_dealer_code , us.sp_region , us.sp_department, sp_business_phone, us.sp_mobile_phone , us.sp_dealer_category, us.sp_email,
sa.npc_item_id , sa.npc_part_no, sa.npc_quantity, sa.npc_customer_name, sa.npc_registration_no , sa.npc_suo_no , sa.npc_amb_club_no , sa.npc_repair_order , sa.npc_invoice_no ,
sa.npc_entry_userdate, sa.npc_image_upload, sa.npc_usertype, sa.npc_points, sa.npc_bonus_points, sa.npc_active, sa.npc_entry_date,
DATE_FORMAT(sa.npc_entry_date, '%d-%m-%Y') AS dr , sa.sp_user_id
FROM sp_user AS us, npc_sales_list AS sa
WHERE us.sp_user_id = sa.sp_user_id
ORDER BY
$order_by LIMIT $start, $display";
$result = #mysql_query ($query);
//
// Table header.
echo '<table width="100%" cellspacing="1" cellpadding="4" style="font-size:10px;">
<tr>
<td align="center"><b>Invoice No.</b></td>
<td align="center"><b>Member ID</b></td>
<td align="center"><b>Surname</b></td>
<td align="center"><b>Part #</b></td>
<td align="center"><b>Sale Type</b></td>
<td align="center"><b>Qty</b></td>
<td align="center"><b>Invoice Date</b></td>
<td align="center"><b>Customer Rego</b></td>
<td align="center"><b>Submission Date</b></td>
<td align="center"><b>Status</b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center"><strong>Details</strong></td> ';
echo '<td align="center"><strong>' . $row['sp_amb_club_no'] . '</strong></td> ';
echo '<td align="center"><strong>' . $row['sp_surname'] . '</strong></td> ';
echo '<td align="center"> <strong>' . $row['npc_part_no'] . '<strong></td>';
echo '<td align="center"> ' . $row['npc_usertype'] . ' </td>';
echo '<td align="center"> ' . $row['npc_quantity'] . ' </td>';
echo '<td align="center"> ' . $row['npc_entry_userdate'] . ' </td>';
echo '<td align="center"> ' . $row['npc_registration_no'] . ' </td>';
echo '<td align="center"> ' . $row['dr'] . ' </td>';
echo '<td align="center" style="color:#5a8e22; font-weight:bold;"> ' . $row['npc_active'] . ' </td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result);
mysql_close();
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view-all-sales.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view-all-sales.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view-all-sales.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
include ('./includes/footer_admin_user.html');
?>