This question already has answers here:
How to find the foreach index?
(14 answers)
Closed 7 years ago.
how to get array index from foreach looping, i use session to print cart data like this, i need to print the index like 1, 2, 3, 4 before the code column in the table
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<tbody>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<tr>';
echo '<td>?</td>';
echo '<td>'.$cart_itm["code"].'</td>';
echo '<td>'.$cart_itm["name"].'</td>';
echo '<td>'.$cart_itm["qty"].'</td>';
echo '<td><input type="text" name="product_qty_desired" class="spinner" value="1" size="3" /></td>';
echo '<td>'.$currency.$cart_itm["price"].'</td>';
echo '<td class="subtotal">Subtotal : </td>';
echo '<td><span class="remove-itm">×</span></td>';
echo '</tr>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td>Total QTY :</td>';
echo '<td></td>';
echo '<td>?</td>';
echo '<td>Total</td>';
echo '<td>'.$currency.$total.'</td>';
echo '<td></td>';
echo '</tr>';
echo '</tbody>';
}else{
echo 'Your Cart is empty';
}
?>
http://i62.tinypic.com/2qaifrt.png
Thanks
Warmly
foreach ($_SESSION["products"] as $index => $cart_itm)
{
echo '<tr>';
echo '<td>' . $index . '</td>';
echo '<td>'.$cart_itm["code"].'</td>';
echo '<td>'.$cart_itm["name"].'</td>';
echo '<td>'.$cart_itm["qty"].'</td>';
echo '<td><input type="text" name="product_qty_desired" class="spinner" value="1" size="3" /></td>';
echo '<td>'.$currency.$cart_itm["price"].'</td>';
echo '<td class="subtotal">Subtotal : </td>';
echo '<td><span class="remove-itm">×</span></td>';
echo '</tr>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
With the arrow operator, you can select the index in a foreach loop.
Related
I'm creating a contact based system, i have a contact list and want it to go to a full contact page when i click on a button, but the variable is being detected as a function?
<div id="po2" style="Margin:10% ">
<h1>Contacts</h1>
<?php
$sql = "SELECT * FROM `contacts`";
$query = mysqli_query($conn, $sql);
echo '<table class="data-table">';
echo'<thead>';
echo'<tr>';
echo '<th>Forename</th>';
echo '<th>Surname</th>';
echo '<th>Other</th>';
echo'</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_array($query))
{
echo '<tr>';
echo '<td>'.$row['Forename'].'</td>';
echo '<td>'.$row['Surname'].'</td>';
echo $var==$row['Forename']("<td><a href='View.php?ID= " . urlencode($var) ."'>
<button type='button'>link</button>
</a></td>");
echo '</tr>';
}
echo'</tbody>';
echo '</table>';
?>
</div>
You are using a comparison of $var and the $row. Try setting $var to the $row each loop iteration.
echo '<thead>';
echo '<tr>';
echo '<th>Forename</th>';
echo '<th>Surname</th>';
echo '<th>Other</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_array($query))
{
$var = $row['Forename'];
echo '<tr>';
echo '<td>' . $var . '</td>';
echo '<td>' . $row['Surname'] . '</td>';
echo "<td><a href='View.php?ID=" . urlencode($var) . "'><button type='button'>link</button></a></td>";
echo '</tr>';
}
echo '</tbody>';
I don't understand, I have a variable $i which is not incrementing in my loop.
while ($ligne = mysqli_fetch_array($resu2,MYSQL_ASSOC)) {
echo '<tr>';
for($i = 1; $nbjour >= $i; $i++)
{
while ($ligne2 = mysqli_fetch_array($resu3,MYSQL_ASSOC)) {
$element=$ligne2['jourIndisponibilite'];
echo "1er ".$element;
echo "2eme ".$ligne['idSPProfessionnel'];
echo ' ';
echo $i;
echo ' ';
if ($ligne2['jourIndisponibilite']==$i && $ligne['idSPPprofessionnel']==$ligne2['idSpProfessionnel']){
echo '<td height=25>';
echo 'X';
echo '</td>';
}
}
echo '<td height=20></td>';
}
echo '</tr>';
}
echo "</table>";
echo '</br>';
?>
I am getting website design ideas from a website API.
Currently my setup displays these designs in a table with only one column, I have over 40 items that need to be displayed in the table, but id prefer to display it in 3 columns. I have tried using i=0 ++ things etc but couldnt work out where to put it.
Here is my code so far:
<?php
$output = json_decode($output);
curl_close($ch);
echo '<table border="1">';
foreach($output as $template) {
echo '<tr>';
echo '<td>' . $template->template_name . '</td>';
echo '</tr>' . '<tr>';
echo '<td><img src="' . $template->thumbnail_url. '">' . '</td>';
echo '<tr>';
echo '<td><form method="GET" action=' . $_SERVER['PHP_SELF'] . '>';
echo '<input type="hidden" name="template_id" value="' . $template->template_id . '">';
echo '<input type="url" name="original_url" placeholder="Existing Site URL">'.'<br />';
echo '<input type="email" name="email" placeholder="Your e-mail" required>'.'<br />';
echo '<button type="submit">Choose Site</button>';
echo '</form></td>';
echo '</tr>';
}
echo '</table>';
}
?>
The output includes all of the website templates.
I am putting it into rows.The first row contains the name of the template, the second the picture of the website template and the third a form which I am working on.
My question is how can I nest the loop so that it does 3 columns, each row with 3 different designs?
Many thanks in advance
The common idea may be as the following, for example:
<?php
$array = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$i = 1;
echo "<table>";
foreach ($array as $arr) {
if ($i % 3 === 0) {
echo "<tr class='class_3'>";
} else if ($i % 2 === 0) {
echo "<tr class='class_2'>";
} else {
echo "<tr class='class_1'>";
}
echo '<td>'.($i++).'</td>';
echo '<td>'.($i++).'</td>';
echo '<td>'.($i++).'</td>';
echo "</tr>";
//$i++; for 123 456
}
echo '</table>';
?>
Update: a more specific example:
<?php
$assoc_array = json_decode('
[
{"template_id": "1","template_name":"A", "preview_url":"url_1"},
{"template_id": "2","template_name":"B", "preview_url":"url_2"},
{"template_id": "3","template_name":"C", "preview_url":"url_3"},
{"template_id": "4","template_name":"D", "preview_url":"url_4"},
{"template_id": "5","template_name":"E", "preview_url":"url_5"},
{"template_id": "6","template_name":"F", "preview_url":"url_6"},
{"template_id": "7","template_name":"G", "preview_url":"url_7"},
{"template_id": "8","template_name":"H", "preview_url":"url_8"},
{"template_id": "9","template_name":"I", "preview_url":"url_9"},
{"template_id": "10","template_name":"J", "preview_url":"url_10"}
]
', true);
echo '<table>';
for($i = 0; $i < sizeof($assoc_array); $i++) {
if ($i % 3 === 0) {
echo "<tr class='class_3'>";
} else if ($i % 2 === 0) {
echo "<tr class='class_2'>";
} else {
echo "<tr class='class_1'>";
}
echo '<td>'.$assoc_array[$i]['template_name'].'</td>';
if(isset($assoc_array[++$i]['template_name'])) {
echo '<td>'.$assoc_array[$i]['template_name'].'</td>';
}
if(isset($assoc_array[++$i]['template_name'])) {
echo '<td>'.$assoc_array[$i]['template_name'].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
You'll get:
A B C
D E F
G H I
J
Thanks everyone who contributed. My answer is now finished.
The final code was:
<?php
$output = json_decode($output);
curl_close($ch);
$i = 0;
echo '<table border="1" width="80%">';
echo '<tr>';
foreach($output as $template) {
echo '<td><img src="' . $template->thumbnail_url. '" height="300" width="460">' .'<br />';
echo '<form method="GET" action=' . $_SERVER['PHP_SELF'] . '>';
echo '<input type="hidden" name="template_id" value="' . $template->template_id . '">';
echo '<input type="url" name="original_url" placeholder="Existing Site URL">'.'<br />';
echo '<input type="email" name="email" placeholder="Your e-mail" required>'.'<br />';
echo '<button type="submit">Choose Site</button>';
echo '</form></td>';
$i++;
if($i == 3) { // three items in a row. Edit this to get more or less items on a row
echo '</tr>'.'<tr>';
$i = 0;
}
}
echo '</tr>';
echo '</table>';
}
?>
This is my current code (and image showing output). I want the table to be aligned and the Names of the values keep repeating. How can I achieve this?
<?php
$country['ph'] = array('Philippines', 'Manila', '+8');
$country['ru'] = array('Russia', 'Moscow', '-4');
$ctr = 1;
foreach ($country as $key => $value) {
echo '<table border = "1" >';
echo '<td>No';
echo '<td>Flag';
echo '<td>Code';
echo '<td>Name';
echo '<td>Capital';
echo '<td>Time Zone';
echo '<tr>';
echo '<td>', $ctr++, '</td>';
echo "<td><img src = \"/csnclass/img/flags/$key.png\"/></td>";
echo "<td>$key</td>";
echo '<td>',$value[0], '</td>';
echo '<td>',$value[1], '</td>';
echo '<td>',$value[2], '</td>';
echo '</tr>';
echo '</table>';
}
?>
Presently, your foreach is outputting a <table> for each item it iterates through - so the table cells in these tables won't be lined up, as cells in different tables have no relation to each other. Similarly, you're outputting the header of each table column for every single item as well.
A quick way to fix this is to take some of the echo calls outside of the foreach loop (mainly relating to the table and headers):
// Start table and print out headers
echo '<table border = "1" >';
echo '<tr>';
echo '<td>No';
echo '<td>Flag';
echo '<td>Code';
echo '<td>Name';
echo '<td>Capital';
echo '<td>Time Zone';
echo '</tr>';
// Print data for each country
foreach ($country as $key => $value) {
echo '<tr>';
echo '<td>', $ctr++, '</td>';
echo "<td><img src = \"/csnclass/img/flags/$key.png\"/></td>";
echo "<td>$key</td>";
echo '<td>',$value[0], '</td>';
echo '<td>',$value[1], '</td>';
echo '<td>',$value[2], '</td>';
echo '</tr>';
}
// End table
echo '</table>';
Hope this helps! Let me know if you have any questions.
Here is my associative array:
$req_data1[]=array(
'depart1'=>$_REQUEST['to'],
'd_time1'=>$d_time5,
'stop'=>"",
'leave_stop'=>"",
'arrival1'=>$_REQUEST['from'],
'a_time1'=>$end_time5,
'price1'=>intval($final_price),
'air_line'=>"xxxxx");
Here is my sorting algorithm:
foreach ($req_data as $key => $row) {
$depart[$key] = $row['depart'];
$d_time[$key] = $row['d_time'];
$stop[$key] = $row['stop'];
$leave_stop[$key] = $row['leave_stop'];
$arrival[$key] = $row['arrival'];
$a_time[$key] = $row['a_time'];
$price[$key] = $row['price'];
}
array_multisort($price,SORT_ASC, $req_data);
I am displaying the data after sorting:
foreach($req_data as $key=>$row) {
echo "</br>";
foreach($row as $key2=>$row2){
echo $row2;
}
}
My problem now is that I want to put that array into an HTML table but dont know how. This is my code which I tried so far but its not working:
$cols = 5;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($r=0; $r < count($row2); $r++) {
echo "<tr>";
for ($c=0; $c<$cols; $c++) {
?> <td> <?php $input[$r+$c] ?> </td> <?php
}
echo "</tr>";
$r += $c;
}
echo "</table>";
?>
Could any one tell me what is wrong with my code, or how I can display this sorted data into a table? Thanks.
Why not just modify the loop you already use to display the data?
echo "<table>";
foreach($req_data as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
$toOutput = '<table>';
$showHeader = true;
$memberData = $reportObj->getMemberData();
while($row = mysql_fetch_assoc($memberData))
{
$toOutput .= '<tr>';
//Outputs a header if nessicary
if($showHeader)
{
$keys = array_keys($row);
for($i=0;$i<count($keys);$i++)
{
$toOutput .= '<td>' . $keys[$i] . '</td>';
}
$toOutput .= '</tr><tr>';
$showHeader = false;
}
//Outputs the row
$values = array_values($row);
for($i=0;$i<count($values);$i++)
{
$toOutput .= '<td>' . $values[$i] . '</td>';
}
$toOutput .= '</tr>';
}
$toOutput .= '</table>';
echo 'Test page';
echo $toOutput;
Sorry for the necro, but I was actually looking to see if there was a build-in function for this as I was writing this.
function DumpTable($array_assoc) {
if (is_array($array_assoc)) {
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
list($table_title) = $array_assoc;
foreach ($table_title as $key => &$value):
echo '<th>' . $key . '</th>';
endforeach;
echo '</tr>';
echo '</thead>';
foreach ($array_assoc as &$master):
echo '<tr>';
foreach ($master as &$slave):
echo '<td>' . $slave . '</td>';
endforeach;
echo '</tr>';
endforeach;
echo '</table>';
return;
}
}
echo "<table border=\"5\" cellpadding=\"10\">";
for ($r=0; $r < count($row2); $r++) {
echo "<tr>";
for ($c=0; $c<$cols; $c++) { ?>
<td> <?php $input[$r+$c] ?> </td>
<?php }
echo "</tr>";
$r += $c;
}
echo "</table>";?>
Try something like this
echo "<table>";
for($r=0;$r<count($row2);$r++){
echo "<tr>";
for($c=0;$c<$cols;$c++){
echo "<td>".[VARIABLE YOU WANT TO PRINT]."</td>";
}
echo "</tr>";
}
echo "</table>";
you can try the following:
echo "The associative array<br>";
$computer=array("brand"=>"hp", "price"=>"800", "cpu"=>"core i7");
$keys=array_keys($computer);
echo "<table><tr>";
foreach($keys as $row){
echo "<th style=\"border: solid 2px green\">".$row."</th>";
}echo "</tr><tr>";
foreach($computer as $col){
echo "<td style=\"border: solid 2px blue\">".$col."</td>";
}echo "</tr></table>";