Find last value of array in foreach cicle - php

I've data stored in a array ($rows).
For read the array and genarate a dinamic table I use foreach function.
<table>
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
</table>
My goal is to find the last value of the array (the end) in order to change the class of TR element for the last line displayed.
How could I do this?
Thanks

Try this:
foreach ($rows as $key => $row) {
$end = end($rows) === $row ? 'class="last"' : '';
echo "<tr $end>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
This method works for multidimentional arrays as well.
http://codepad.org/HQG9ytBX
Edit. As pointed in comments, this approach may potentially trigger false end result if some values in the array are duplicated (with the last). Correct bullet-proof version should be:
foreach ($rows as $key => $row) {
$end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';
// ...

foreach ($rows as $row) {
$is_last_row = ++$i == count($rows);
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
here $i should be an unused variable.

Try This
$numItems = count($rows);
$i = 0;
foreach($rows as $row) {
$trClass = 'firstclass';
if(++$i === $numItems)
{
$trClass = 'lastclass';
}
echo "<tr class='$trclass'>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}

// first, let's find out the last key
end($rows);
$last = key($rows);
// then just loop over
foreach ($rows as $key => $row) {
if ($key == $last) {
// last leaf of the summer...
}
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}

Related

Printing alphabets from a to z every time

I am using the below php code to list Alphabetical(A-Z) characters in the rows. It works fine from a to z. My problem is that after "z", it starts with aa, ab,ac, etc.. I'd like it to start with a to z again every time it comes to z.
How can achieve this? thanks.
<?php
foreach (range('a', 'z') as $char)
while($row = mysqli_fetch_array($search_result))
{
echo "<tr>";
echo "<td>" .$char. "</td>";
$char++;
echo "<td>" . $row['Rp1'] . "</td>";
echo "<td>" . $row['Rp2'] . "</td>";
echo "<td>" . $row['Rp3'] . "</td>";
echo "<td>" . $row['Rp4'] . "</td>";
echo "</tr>";
}
?>
I tried below solution but it ended up with the same result.
<?php
$char= 'a';
for($i=0;$i<26;$i++)
while($row = mysqli_fetch_array($search_result))
{
echo "<tr>";
echo "<td>" .$char. "</td>";
$char++;
echo "<td>" . $row['Rp1'] . "</td>";
echo "<td>" . $row['Rp2'] . "</td>";
echo "<td>" . $row['Rp3'] . "</td>";
echo "<td>" . $row['Rp4'] . "</td>";
echo "</tr>";
}
?>
You could utilize PHP's built-in array functions for handling internal array pointers:
$range = range('a', 'z');
while ($row = mysqli_fetch_array($search_result)) {
echo "<tr>";
echo "<td>" . current($range) . "</td>";
echo "<td>" . $row['Rp1'] . "</td>";
echo "<td>" . $row['Rp2'] . "</td>";
echo "<td>" . $row['Rp3'] . "</td>";
echo "<td>" . $row['Rp4'] . "</td>";
echo "</tr>";
if (next($range) !== false) {
reset($range);
}
}
Checkout these references to learn more:
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.next.php
http://php.net/manual/en/function.reset.php
You can reference your array of letters by a calculated value, $i % 26, where $i is the zero based iteration count of your while loop.
$letters = range('a', 'z');
$i = 0;
while ($row = mysqli_fetch_array($search_result)) {
echo "<tr>";
echo "<td>" . $letters[$i++ % 26] . "</td>";
echo "<td>" . $row['Rp1'] . "</td>";
echo "<td>" . $row['Rp2'] . "</td>";
echo "<td>" . $row['Rp3'] . "</td>";
echo "<td>" . $row['Rp4'] . "</td>";
echo "</tr>";
}
Firstly, get the characters from a to z in an array.
Initialize a counter (index) to access a specific character from the array.
Increment the counter inside loop.
If the counter value goes above 25 (index starts from 0 - so this represents 26th array item), reset its value back to zero.
Try the following:
<?php
// get array for characters from a to z
$characters = range('a', 'z');
$counter = 0; // initialize the counter (index)
while($row = mysqli_fetch_array($search_result))
{
echo "<tr>";
// access the character using counter index
echo "<td>" . $characters[$counter] . "</td>";
// Increment the counter
$counter++;
// Check and reset if the counter has gone above 25 (26th array item)
$counter = ($counter > 25 ? 0 : $counter);
echo "<td>" . $row['Rp1'] . "</td>";
echo "<td>" . $row['Rp2'] . "</td>";
echo "<td>" . $row['Rp3'] . "</td>";
echo "<td>" . $row['Rp4'] . "</td>";
echo "</tr>";
}
?>

Get data from SQL database of multiple columns stored in explode function using PHP

I am using this code to get that data from SQL Server database using PHP
<?php
foreach ($dbDB->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['Country'] . "</td>";
echo "<td>" . $row['OrderNumber'] . "</td>";
echo "<td>" . $row['Region'] . "</td>";
echo "<td>" . $row['ShipDate'] . "</td>";
echo "<td>" . $row['ProducedDate'] . "</td>";
echo "</tr>"; }
?>
I am trying to replace these multiple lines but storing the columns' names in a string for example $_POST['SelectedColumns'].
The values coming into post as comma separated string, For example : Country,OrderNumber,Region,ShipDate,ProducedDate
I have tried this solution but still not working for me.
<?php
$ser="********";
$db="******";
$user="******";
$pass="******";
$query = 'SELECT '.$_POST['SelectedColumns'].' FROM reporting.REPORT_ALL';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=******;Port=1456", $user, $pass);
$row = $_POST["SelectedColumns"];
$rows = explode(",",$row);
/*Here I have the another html code independent of this part */
foreach ($dbDB->query($query) as $dataRow) {
echo "<table>";
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
echo "</table>"; }
?>
Any suggestions please ?

How to deal with arrays in PHP language

<?php
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q1 = "SELECT * FROM student_record INNER JOIN degree_plan ON
student_record.course_number = degree_plan.course_number
INNER JOIN courses ON student_record.course_number =
courses.course_number where student_record.id = 201102887 AND degree_plan.major='COE'";
$result = mysqli_query($con , $q1 ) ;
$data = array();
while($row = mysqli_fetch_array($result))
{
$data[$row["term_no"]][] = array(
'code' => $row["code"],
'grade' => $row["grade"]
);
}
echo '<table width="200" border="1">';
echo "<tr>";
echo "<th>courses</th>";
echo "<th>terms</th>";
echo "<th>grades</th>";
echo "</tr>";
foreach($data as $term=>$otherrow) {
$count = 0;
foreach ($otherrow as $data) {
if($count == 0) {
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}
$count++;
}
}
echo "</table>";
?>
I have this code and it work very well but I faced problem when I want to add more column .
I tried to add fourth column(echo "<td>" . $row["crd"]. "</td>"; ) but there is no result .It give me empty cells. how I can do that?
I want add add this echo "<td>" . $row["crd"]. "</td>"; column to my code.
As mentioned in the comments, there are two errors that have been noticed.
You are re-declaring $data in your second foreach loop
You don't have $row initiated anywhere, and atempting to echo $row["crd"] will result in an empty cell.
Proposed Solution:
Change the name of the $data value in the foreach loop to $row and hence solve both problems at the same time:
foreach($data as $term=>$otherrow) {
$count = 0;
foreach ($otherrow as $row) {
if($count == 0) {
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
$count++;
}
}
And when you add echo "<td>" . $row["crd"]. "</td>"; now it should echo the value stored in the $row array (as long as the value was extracted from the table in the database in the first place of course).
Let me know if this worked for you.

rowCount based on row value

So I am trying to do this..
$userID = $_SESSION['user_session'];
$stmt = $this->db->prepare("SELECT * FROM orrs");
$stmt->bindparam(":id", $userID);
$stmt->execute();
$count = $stmt->rowCount();
echo
"<div class='table-responsive'>
<table class='table' border='1'>
<tr class='head'>
<h3>Snapshot</h3>
<th>Se</th>
<th>#s</th>
<th>Ae</th>
<th>Prt</th>
<th>Pin</th>
</tr>";
while($userRows=$stmt->fetch(PDO::FETCH_ASSOC)) {
if($userRows['stage'] == '1')
{
echo "<tr>";
echo "<td>" . "Newn" . "</td>";
echo "<td>" . $count . "</td>";
echo "<td>" . $userRows['aow'] . "</td>";
echo "<td>" . $userRows['pit'] . "</td>";
echo "<td>" . $userRows['pgin'] . "</td>";
}
else if($userRows['stage'] == '2')
{
echo "<tr>";
echo "<td>" . "Pendinn" . "</td>";
echo "<td>" . $count . "</td>";
echo "<td>" . $userRows['gfh'] . "</td>";
echo "<td>" . $userRows['pt'] . "</td>";
echo "<td>" . $userRows[trin'] . "</td>";
}
}
Basically, If the value in the row STAGE = 1 I want it to count those rows and give me the number.. If the value of STAGE = 2 I want it to count those rows and give me the number.
Right now, It is just counting all of the rows.. So for both of the IF statment its count number is saying 2, When there is only 1 in each section..
I think you need to execute three different statements, one to get all the rows (for you to loop over and create your output) and one to get each of the counts
//The current one
$stmt = $this->db->prepare("SELECT * FROM orrs");
//The get the count for stage '1'
$stage_1_stmt = $this->db->prepare("SELECT * FROM orrs where STAGE = 1");
$stage_1_count = $stage_1_stmt->rowCount();
//The get the count for stage '2'
$stage_2_stmt = $this->db->prepare("SELECT * FROM orrs where STAGE = 2");
$stage_2_count = $stage_2_stmt->rowCount();
You can execute these others to get the counts which you should use in place of $count in your loop.
Your while loop then becomes
while($userRows=$stmt->fetch(PDO::FETCH_ASSOC)) {
if($userRows['stage'] == '1')
{
echo "<tr>";
echo "<td>" . "Newn" . "</td>";
echo "<td>" . $stage_1_count . "</td>";
echo "<td>" . $userRows['aow'] . "</td>";
echo "<td>" . $userRows['pit'] . "</td>";
echo "<td>" . $userRows['pgin'] . "</td>";
}
else if($userRows['stage'] == '2')
{
echo "<tr>";
echo "<td>" . "Pendinn" . "</td>";
echo "<td>" . $stage_2_count . "</td>";
echo "<td>" . $userRows['gfh'] . "</td>";
echo "<td>" . $userRows['pt'] . "</td>";
echo "<td>" . $userRows[trin'] . "</td>";
}
}

PHP - How do I get this to print out in a table from an reference number?

echo '<td><input type="checkbox" name="items[]" value="' . $row['0'] . '" /></td>';
Hi, I'm trying to get a reference number which comes from a an array called items from another page as shown above, and to find it in the table and print out the reference row, like "Title,Platform...." into another table, but I can't seem to get it working...any help be appreciated
if (isset($_POST['items'])) {
$n = count($_POST['items']);
for($i=0; $i < $n; $i++){
// echo $_POST['items'][$i];
}
$items = array();
foreach ($_POST['items'] as $item) {
$items[] = pg_escape_string($con, $item);
}
if (!$_SESSION["selectingrows"]) {
$item_string = "'" . implode("','", $items) . "'";
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' IN ($item_string)");
while($rows = pg_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $rows['1'] . "</td>";
echo "<td>" . $rows['2'] . "</td>";
echo "<td>" . $rows['3'] . "</td>";
echo "<td>" . $rows['4'] . "</td>";
echo "</tr>";
}
}
}
One thing, you need to put {} braces after your while loop.
Here is what you are doing:
while($rows = pg_fetch_assoc($result))
echo"<tr>"; echo "<td>" . $rows['1'] . "</td>"; echo "<td>" . $rows['2'] . "</td>"; echo "<td>" . $rows['3'] . "</td>"; echo "<td>" . $rows['4'] . "</td>";
echo"</tr>";
By not putting braces around the code after the while statement, here is what your code really does:
while($rows = pg_fetch_assoc($result))
{
echo"<tr>";
}
echo "<td>" . $rows['1'] . "</td>"; echo "<td>" . $rows['2'] . "</td>"; echo "<td>" . $rows['3'] . "</td>"; echo "<td>" . $rows['4'] . "</td>";
echo"</tr>";
You should always put braces in to define what code is in the while loop.
You want your code to be something like this:
while($rows = pg_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $rows['1'] . "</td>";
echo "<td>" . $rows['2'] . "</td>";
echo "<td>" . $rows['3'] . "</td>";
echo "<td>" . $rows['4'] . "</td>";
echo "</tr>";
}
Format your code neatly and properly. By doing this your code is clearer and it is much easier to notice possible mistakes like the above. Always use braces for if, while, for statements. When putting an end line semicolon ; put in a new line break. Indent your code correctly. It's little things like formatting that make coding easier.
Now the next problem I can see is the values you are getting from the $rows array:
$rows['1'];
$rows['2'];
$rows['3'];
$rows['4'];
This is trying to get something from the $rows array which has the key of string '1'.
Usually you access array values by index, which uses an integer beggining from 0. Or you access it by a key.
Either you can try this:
$rows[0];
$rows[1];
$rows[2];
$rows[3];
Or this:
$rows['title'];
$rows['platform'];
$rows['description'];
$rows['price'];

Categories