I have this async code , but when i try to render inside a table , the table become a mess (image) but after a page refresh the table is perfctly fine and i dont know why , how can i fix this problem ?
and if is possible to have a better async code , i know i need to async the
$api->getMatchTimeline($match->gameId); but i don't know how can i do it.
<table class="table table table-bordered" style="width:100%">
<tr>
<thead>
<th>Items</th>
</thead>
</tr>
<tbody>
<?php
$onSuccess = function (Objects\MatchDto $match) use (&$api, $champ) {
echo "<tr>";
echo "<td>";
foreach ($match->participants as $partId) {
if ($partId->championId == $champ) {
$participant_id = $partId->stats->participantId;
$pp = $api->getMatchTimeline($match->gameId);
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_id) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
$depth = $d->depth;
if (($depth == 3 or $depth == 2)) {
echo "<a href = https://lolprofile.net/match/kr/$match->gameId#Match%20History >";
echo "<img src =" . DataDragonAPI::getItemIconUrl($item_id) . " />" . '</a>';
}
}
}
}
}
}
echo "</td>";
echo "</tr>";
};
$onFailure = function ($ex) {
echo $ex;
};
foreach ($database as $game) {
$api->nextAsync($onSuccess);
$match = $api->getMatch($game->match_ids);
}
$api->commitAsync();
?>
</tbody>
</table>
render outside the table
The problem isn't to do with your "async" PHP code, but because your <table> markup is incorrect.
HTML's <table> element has two different forms. The first is the "implicit <tbody> form, like this:
<table>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
The other has an explicit <tbody> element, which can also optionally have a <thead> and <tfoot> (you can also have multiple <tbody> but only a single <thead>. You can use a <thead> and <tfoot> with an implicit <tbody> but this is not recommended - I recommend everyone use the explicit syntax, like so:
<table>
<tbody>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</tbody>
</table>
Note that the actual DOM representation of both tables is the same: in the DOM a <table> never has <tr> as immediate children.
Secondarily, you can also make your code a LOT easier to read and follow if you separate your application logic from your rendering logic by doing all of your API calls and whatnot at the start of your PHP script and populate a "view model" object and then the rendering logic is greatly simplfied, like so:
<?php
// This PHP block should be before *any* HTML is written:
class MatchAndItems {
public Objects\MatchDto $match;
public Array $items;
}
$allMatches = Array(); # Array of `MatchAndItems`.
$onFailure = function ($ex) {
echo $ex;
};
$gotMatch = function (Objects\MatchDto $match) use (&$api, $champ, $allMatches) {
$e = new MatchAndItems();
$e->match = $match;
$e->items = array();
foreach ($match->participants as $partId) {
if ($partId->championId == $champ) {
$participant_id = $partId->stats->participantId;
$pp = $api->getMatchTimeline($match->gameId);
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_id) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
array_push( $e->items, $d );
}
}
}
}
}
array_push( $allMatches, $e );
};
# Set-up web-service HTTP request batches:
foreach( $database as $game ) {
$api->nextAsync( $gotMatch )->getMatch( $game->match_ids );
}
# Invoke the batch:
$api->commitAsync();
# The below code uses https://www.php.net/manual/en/control-structures.alternative-syntax.php
?>
<!-- etc -->
<table class="table table table-bordered" style="width: 100%">
<thead>
<tr>
<th>Items</th>
</tr>
</thead>
<tbody>
<?php foreach( $allMatches as $match ): ?>
<tr>
<td>
<?php
foreach( $match->items as $item ):
if( $item->depth == 2 or $item->depth == 3 ):
echo "<a href = https://lolprofile.net/match/kr/$match->gameId#Match%20History >";
echo "<img src =" . DataDragonAPI::getItemIconUrl($item_id) . " />" . '</a>';
endif;
endforeach;
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
Related
i have this table wrote in html with php and bootstrap:
<table id="tabela-resultado" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>Ativo</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if(count($records)) { ?>
<?php foreach($records as $record) { ?>
<tr data-id="<?php echo $record->id; ?>">
<td><?php echo $record->nome; ?></td>
<td>
<?php
if ($record->ativo == 1) {
echo "SIM";
} else if($record->ativo == 0){
echo "NÂO";
}
?>
</td>
<td>
<?php echo anchor("gurpoProduto/excluir", "<i class='glyphicon glyphicon-trash'></i> Exlcuir", ['class' => 'btn btn-danger btn-block', 'name' => 'delete']); ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
i'm trying to found an element in the first column using this function with jquery. Tihs is the function:
function verificar_existencia(nome) {
var table = $("#tabela-resultado tbody");
var nomeTabela = '';
table.find('tr').each(function (nome) {
var $tds = $(this).find('td'),
nomeTabela = $tds.eq(0).text()
});
if(trim(nome.toUpperCase()) === trim(nomeTabela.toUpperCase())) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
but doesnt work.Whats is wrong? I need find an element in the table to prevent duplicate elements in the table.
You are looping through all the rows and overwriting nomeTabela every iteration.
Thus once loop completes it is the value found in last row only and that is what your comparison is done on
Do a check inside the loop for each value on each row something like:
function verificar_existencia(nome) {
nome = nome.trim().toUpperCase();
var table = $("#tabela-resultado tbody");
var isMatch = false;
table.find('tr').each(function(nome) {
var $tds = $(this).find('td');
var nomeTabela = $(this).find('td').eq(0).text();
// compare each value inside the loop
if (nome === nomeTabela.trim().toUpperCase()) {
isMatch = true;
return false; /// break the loop when match found
}
});
if (isMatch) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
Also note your incorrect use of String#trim() which should show up as error in your browser console
Here's a way to identify a dupe strings in the first column of the table.
var $trs = $("table tr"), dupes = [];
function san(str) {
return str.text().trim().toUpperCase();
}
$trs.each(function() {
var origTd = $(this).find("td:first"), origTr = $(this);
$trs.each(function() {
var newTd = $(this).find("td:first"),
newTr = $(this),
origTrIdx = origTr.index(),
newTrIdx = newTr.index(),
origTdStr = san(origTd),
newTdStr = san(newTd);
if (
origTrIdx > newTrIdx &&
dupes.indexOf(origTdStr) < 0 &&
origTdStr === newTdStr
) {
dupes.push(origTdStr);
console.log(
'This element "' +
origTd.text() +
'" already exists!!!'
);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>unique</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</table>
I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
Any ideas?
Expected output is a simple 3X3 table with the values from the array
Use this you may looking for this
<?php
echo('<table><tr>');
$i = 0;
foreach( $array as $product )
{
$i++;
echo '<td>'.$product .'</td>';
if($i % 3==0)
{
echo '</tr><tr>';
}
}
echo'</tr></table>';
?>
Result Here:
<table>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
</table>
This should work for you:
(See that I added a tr at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.)
<?php
$array = ['0','1','2','3','4','5','6'];
$table = "<table class='table'><tbody><tr>";
//^^^^ See here the start of the first row
foreach($array as $a => $v) {
$table .= "<td>$v</td>";
//^ ^ double quotes for the variables
if(($a+1) % 3 == 0)
$table .= "</tr><tr>";
}
$table .= "</tr></tbody></table>";
//^ ^^^^^ end the row
//| append the text and don't overwrite it at the end
echo $table;
?>
output:
<table class='table'>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
</tbody>
</table>
Here is an easy solution with array_chunk():
<?php
$array = array('0','1','2','3','4','5','6');
$d = array_chunk($array, 3);
$table = "<table border='1' class='table'><tbody>";
foreach($d as $v)
$table .= "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";
$table .= "</tbody></table>";
echo $table;
?>
Here is an easy solution with incrementing that works with a dynamically generated table like the one in Magento product view page to help display product attributes in two table columns preceded by attribute label -> practically we have 4 table columns together with attribute labels. This is useful for products with multiple attributes that take a long page to display.
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="table table-bordered table-hover" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php $i = 1; ?>
<tr>
<?php foreach ($_additional as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<th style="width: 20%;"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data" style="width:20%;"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
<?php $i++; if($i > 1 && ($i & 1) ) echo "</tr><tr>";?>
<?php } ?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
I have got a question regarding setting up proper categories for my posts that would be done automatically. I'm using PHP.
Here is my sample example document from the database:
{
"_id" : "css-clearfix-explained",
"title" : "CSS Clearfix Explained",
"category" : [
"CSS/HTML",
" Wordpress"
],
"date_time" : ISODate("2014-08-13T21:03:45.367Z"),
"description" : "Blalalal ",
"content" : " ",
"author" : "Maciej Sitko"
}
So, for that purpse I wrote the code that inserts the categories in the view page, to be more specific, it inserts them into the table. This is the code:
<?php if(!isset($_GET['cat'])) {
$categories = $collection->find();?>
<table class="table table-hover table-striped">
<thead class='table-head' >
<tr ><th colspan='2'>Categories</th></tr>
</thead>
<tbody>
<?php foreach($categories as $category) {
foreach($category as $keys) {
if((is_array($keys)) && (!empty($keys))) {
foreach($keys as $key => $value) { ?>
<tr>
<td><a class="normalize" href="">
<?php echo $keys[$key]; ?></a></td>
<td class="small"> Posts</td>
</tr>
<?php } } } } ?>
</tbody>
</table>
The problem is, and you see it (I bet it), that when it is executed this way there would be duplicates of the categories in the table shown. How can I prevent those categories from repeating themselves in the listing? I know its a rookie question, but I'm still learning.
You could write $category into an array and every iteration - before displaying your data - you could check if $category is already in there. You could use "in_array": http://php.net/manual/de/function.in-array.php
<?php if(!isset($_GET['cat'])) {
$categories = $collection->find();?>
<table class="table table-hover table-striped">
<thead class='table-head' >
<tr ><th colspan='2'>Categories</th></tr>
</thead>
<tbody>
<?php
$uniqueCats = array();
foreach($categories as $category) {
foreach($category as $keys) {
if((is_array($keys)) && (!empty($keys))) {
foreach($keys as $key => $value) {
if( in_array($value, $uniqueCats) ) { continue; }
$uniqueCats[] = $value;
?>
<tr>
<td><a class="normalize" href="">
<?php echo $value; ?></a></td>
<td class="small"> Posts</td>
</tr>
<?php } } } } ?>
</tbody>
</table>
I hope that's what you were looking for :)
The code/variables slightly differs from how I would read the data in the example so I might have misinterpreted your question :)
I'm just learing to use php, and I've been working on this code that is not very efficient because it is very long and I would like it to be more automated. The idea is to generate a table with 2 colums, one with the user name and the other with the score of each user. As you may imagine, the score is based on a function that use other variables of the same user. My goal is to only have to set one variable for each user and a new row is would be created automatically at the end of the table.
<?php
$array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest
$array1['BBB'] = "bbb"; ## should be automatic
$array1['ETC'] = "etc";
function getscore($array1){
## some code
return $score;
};
$score['AAA'] = getscore($array1['AAA']);
$score['BBB'] = getscore($array1['BBB']);
$score['ETC'] = getscore($array1['ETC']);
?>
<-- Here comes the HTML table --->
<html>
<body>
<table>
<thead>
<tr>
<th>User</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td> <-- user name should be set automaticlly too -->
<td><?php echo $score['AAA'] ?></td>
</tr>
<tr>
<td>BBB</td>
<td><?php echo $score['BBB'] ?></td>
</tr>
<tr>
<td>ETC</td>
<td><?php echo $winrate['ETC'] ?></td>
</tr>
</tbody>
</table>
</body>
</html>
Any help would be welcome!
$outputHtml = ''
foreach( $array1 as $key => $val )
{
$outputHtml .= "<tr> ";
$outputHtml .= " <td>$key</td>";
$outputHtml .= " <td>".getscore($array1[$key]);."</td>";
$outputHtml .= " </tr>";
}
then in $outputHtml will be html content with all rows you wanna display
This is a little cleaner, using foreach and printf:
<?php
$array1 = array(
['AAA'] => "aaa",
['BBB'] => "bbb",
['ETC'] => "etc"
);
function getscore($foo) {
## some code
$score = rand(1,100); // for example
return $score;
};
foreach ($array1 as $key => $value) {
$score[$key] = getscore($array1[$key]);
}
$fmt='<tr>
<td>%s</td>
<td>%s</td>
</tr>';
?>
<-- Here comes the HTML table --->
<html>
<body>
<table><thead>
<tr>
<th>User</th>
<th>Score</th>
</tr></thead><tbody><?php
foreach ($array1 as $key => $value) {
printf($fmt, $key, $score[$key]);
}
?>
</tbody></table>
</body>
</html>
Also, I'll just note that you don't seem to be using the values of $array1 anywhere. Also,
I'm not sure what $winrate is in your code, so I ignored it.
I would like to alternate the row color from odd and even from the following xml with php.
<?php
// load SimpleXML
$books = new SimpleXMLElement('books.xml', null, true);
echo <<<EOF
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Price at Amazon.com</th>
<th>ISBN</th>
</tr>
EOF;
foreach($books as $book) // loop through our books
{
echo <<<EOF
<tr>
<td>{$book->title}</td>
<td>{$book->author}</td>
<td>{$book->publisher}</td>
<td>\${$book->amazon_price}</td>
<td>{$book['isbn']}</td>
</tr>
EOF;
}
echo '</table>';
?>
How would I do this with php considering my source is XML?
Add a counter, initialize it to zero, increment on each iteration and put different classes in tr depending on the value of $counter%2 (zero or not). (like ($counter%2)?'odd':'even').
Something like this:
for($i=0;$i<6;$i++)
{
if($i % 2)
{
// even
}else{
// odd
}
}
Here's a simple way.
<?php
// load SimpleXML
$books = new SimpleXMLElement('books.xml', null, true);
echo <<<EOF
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Price at Amazon.com</th>
<th>ISBN</th>
</tr>
EOF;
$even = true;
foreach($books as $book) // loop through our books
{
$class = $even ? 'even' : 'odd';
$even = $even ? false : true;
echo <<<EOF
<tr class="$class">
<td>{$book->title}</td>
<td>{$book->author}</td>
<td>{$book->publisher}</td>
<td>\${$book->amazon_price}</td>
<td>{$book['isbn']}</td>
</tr>
EOF;
}
echo '</table>';
?>