Jump to content

Recommended Posts

Hi everyone,

 

I am trying to create two column in php with for loop. seem it is not really work very good because it is repeating. I need to create one value in each value, not repeat.

 

what I need is in output:

 

| value1 | value2 |

| value3 | value4 |

 

but I made an ouput:

 

| value1 | value2 |

| value1 | value2 |

 

Please forgive me for my english error because it is not my prime language, I am using sign language - American Sign Language.

 

Here my code:

 

 <?php
 
require('require.php');
 
$list = "select FirstName, LastName from Members";
$display = mysqli_query($GaryDB,$list);
 
if(mysqli_num_rows($display)) {
    while($list2 = mysqli_fetch_assoc($display)) {
        for($x = 2; $x < 3; $x++) {
            echo "<tr>";
            for($y = 1; $y < 3; $y++) {
                echo "<td>".$list2['FirstName']." ".$list2['LastName']."</td>";
            }
            echo "</tr>";
        }
    }
}
 
 

Any help will be very appreciate!

 

Thank you so much!

 

Gary Taylor

Edited by gizmola
[php] -> [code]
Link to comment
https://forums.phpfreaks.com/topic/304355-two-column-in-table-in-php/
Share on other sites

Try a structure more like this:

 

$display = do query
if rows {
	<table>

	$list2 = first row
	do {
		<tr>

		for $x = 1; $x <= number of columns; $x++ {
			<td>
			if $list2 {
				values from $list2
			} else {
				empty cell
			}
			</td>

			$list2 = next row
		}

		</tr>
	} while ($list2);

	</table>
}

You do realize that the fetch only retrieves one row at a time?  I don't know why you have the loop inside the loop.

 

While ($row = fetch)

{

  echo "<tr>";

  echo "<td>" . $row['firstname']. "</td><td>" . $row['lastname']."</td>";

  echo "</tr>";

}

This would give you the two across rows that you appear to  be asking for.


//Set number of columns for the output
$columns = 2;
 
require('require.php');
 
$query = "SELECT FirstName, LastName FROM Members";
$result = mysqli_query($GaryDB, $query);
 
if(mysqli_num_rows($result))
{
    //dump records into array
    $records = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $records[] = $row;
    }
    //Chunk the array by column count and create output
    $output = '';
    foreach(array_chunk($records, $columns) as $row)
    {
        $output .= "<tr>\n";
        foreach($row as $record)
        {
            $output .= "<td>{$row['FirstName']} {$row['LastName']}</td>\n";
        }
        $output .= "</tr>\n";
    }
}
Edited by cyberRobot
removed extra equal signs (eg. $output = .= "<tr>\n";)
  • Like 1

Dumping everything into an array and then looping through it seems like a waste of time and resources to me. 

 

I'd do it like this. This is with an array, but it gives you the concept. 

 

<?php
 
$data = array('Person 0','Person 1','Person 2','Person 3','Person 4','Person 5','Person 6');
 
$count = 0;
echo "<table border=\"1\">\n";
foreach($data as $p) {
  if($count % 2 == 0) { echo "<tr>\n"; }
  echo "<td>{$p}</td>\n";
  if($count % 2 == 1) { echo "</tr>\n"; }
  $count++;
}
if($count % 2 == 1) { echo "<td> </td>\n</tr>\n"; }
echo '</table>';
?>
Output:

<table border="1">
 <tr>
  <td>Person 0</td>
  <td>Person 1</td>
 </tr>
 <tr>
  <td>Person 2</td>
  <td>Person 3</td>
 </tr>
 <tr>
  <td>Person 4</td>
  <td>Person 5</td>
 </tr>
 <tr>
  <td>Person 6</td>
  <td> </td>
 </tr>
</table>
Essentially, you keep a counter as you loop through your results. On EVEN increments through the loop, you start a table row and on ODD increments, you end the table row.

 

There's an extra check at the end to add an empty cell and close out the table row if the overall number of results were ODD.

Edited by Sepodati

Dumping everything into an array and then looping through it seems like a waste of time and resources to me. 

 

I was going to do it the way you showed - which is how I always used to do it. But, there is a very good reason I do not to do it that way (most of the time). That way requires multiple if() statements to determine the beginning of a row, the end of a row and to determine if the loop ended without properly closing the row. With a relatively simple output such as this the logic for those statements isn't too complex. With a more complicated output the logic can become unwieldy. E.g. if you dealing with 'rows' that are created with multiple levels of DIVs, the logic for closing a row and handling the last row when there are uneven number of elements. By using array_chunk() it takes all the complexity out of the problem. Just loop through the chunks with a single process to start a row, output the data and close the row - whether it is a table row or a more complicated structure.

 

Plus, without bench-marking you have no idea which is more efficient. The if() statements could be more resource intensive than the other method.

Here's a slightly different version of Psycho's solution:

<?php
//Set number of columns for the output
$columns = 2;
 
require('require.php');
 
$query = "SELECT FirstName, LastName FROM Members";
$result = mysqli_query($GaryDB, $query);
 
//dump records into array
$records = array();
while($row = mysqli_fetch_assoc($result)) {
    $records[] = "<td>{$row['FirstName']} {$row['LastName']}</td>";
}
 
//Chunk the array by column count and create output
$output = '';
if(!empty($records)) {
    foreach(array_chunk($records, $columns) as $row) {
        $output .= "<tr>" . implode($row) . "</tr>\n";
    }
}
?>
  • Like 1
  • 2 weeks later...

Sepodati and Psycho,

I found a way to solution my problem. Hey, Psycho, I used your method of array at top of script of php, then I used Sepodati's body of foreach, it works! Let me show you a code:

 

<?php
 
require('require.php');
$list = "select FirstName, LastName from Members";
$display = mysqli_query($GaryDB,$list);
 
$record = array();
 
$count = 0;
if(mysqli_num_rows($display)) {
while($row = mysqli_fetch_assoc($display)) {
$record[] = $row;
}
foreach($record as $z) {
if($count % 2 == 0) {
echo "<tr>";
}
echo "<td>".$z['FirstName']." ".$z['LastName']."</td>";
if($count % 2 == 1) {
echo "</tr>";
}
$count++;
}
if($count % 2 == 1) {
echo "<td> </td></tr>";
}
}
 
 ?>
Edited by sigmahokies

This combination doesn't make any sense, because now you have all the bad parts: The inefficiency of Psycho's solution and the complexity of Sepodati's solution.

 

Don't just blindly copy and paste code. Try to actually understand what it does. In this particular case, I'd go with Psycho's approach, because it's more straightforward.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.