Display PHP Data in 2 Columns - php

Here's my code:
echo "<table><tr>";
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
extract($row);
$data = $row['info'];
echo "<td>".$data."</td>";
if ($count++ % 2 == 0) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
The above code works as:
=========
= 1 = 2 =
= 3 = 4 =
= 5 = 6 =
=========
But how do I display the info in this format?
=========
= 1 = 4 =
= 2 = 5 =
= 3 = 6 =
=========

Actually, you don't need to parse array to another form...
<?php
$a = array(1,2,3,4,5,6,7);
$c = ceil(count($a)/2);
echo "<table>";
for($i=0; $i<$c;++$i){
echo "<tr><td>{$a[$i]}</td><td>{$a[$i+$c]}</td></tr>";
}
echo "</table>";
?>
Ofcourse you need to modify this code by adding db operations (like mysql_num_rows instead of count) but it works fine: enter link description here

Thanks, guys! I appreciate all your help, but this code works perfect for me. I just want to share it with others who may find this helpful. :)
$tmp=array();
$columns=2;
$row=ceil(mysql_num_rows($result)/$columns);
for ($x =1; $x <= $columns; $x++)
for ($y = 1; $y <= $row; $y++)
$tmp[$x][$y]=mysql_fetch_array($result);
echo "<table align=center width=\"50%\">\n";
for ($y =1; $y <= $row; $y++) {
echo "<tr>";
for ($x = 1; $x <= $columns; $x++)
if (isset($tmp[$x][$y]['ID']))
echo "<td>".$tmp[$x][$y]['info']." </a></td>";
else
echo "<td></td>";
echo "</tr>\n";
}
echo "</table>\n";

A brief PSA... the mysql_ extension is depreciated and will eventually be removed. You need to start using mysqli_ now.
You need to parse your data first. Once you've done that, generating the table is easy. This should work for all data sets
echo "<table>";
$count = 1;
$col1 = $col2 = array();
$rowcount = round(mysql_num_rows($result) / 2);
while($row = mysql_fetch_assoc($result)) {
if($count > $rowcount) $col2[] = $row['info'];
else $col1[] = $row['info'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $row) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td>" . $row . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";

This is untested, but you can acheive this cleanly with 2 loops. Build up the left and right columns based on the the $count variable. Build the HTML all the way up, then echo it.
Edit: I didn't realize you were dividing the data in half and placing the first half on the left column of the table. I have changed the code below to do this.
<?php
$left = array();
$right = array();
$count = 1;
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($count <= $num_rows/2) {
array_push($left, $row['info']);
} else {
array_push($right, $row['info']);
}
$count++;
}
$html = "<table>";
for ($i = 0; $i < $count; $i++) {
$html .= "<tr><td>"
. htmlentities($left[$i])
. "</td><td>"
. htmlentities($right[$i])
. "</td></tr>";
}
$html .= "</table>";
echo $html;
?>

Here is some php magic that could shorten that code for a bit
<?php
$array = range(1, 20);
$count = 2;
$out = array_chunk($array, ceil(count($array)/$count));
array_unshift($out, null);
$out = call_user_func_array("array_map", $out);
?>
<table>
<?php foreach ($out as $row) : ?>
<tr>
<?php foreach($row as $column) : ?>
<td><?php echo( $column ); ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Also, i would recommend you switch your database-related code to PDO. Besides all those nice features, like auto-escaping, you can easily get an array of elements from your DB query, without all this mysql_fetch_array nonsense.

Related

PHP get min and max values from 50 random numbers?

<?php
echo "<table border='1'><br />";
for ($row = 0; $row < 10; $row ++) {
echo "<tr>";
for ($col = 0; $col < 5; $col ++) {
$rand = rand (1, 200);
echo "<td>", $rand, "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Here is code but my question is how can I find max and min from values of the table? Do I have to make random numbers somehow into array?
You can do as following without changing much of your code
<?php
$array = array(); // <-- added code
echo "<table border='1'><br />";
for ($row = 0; $row < 10; $row ++) {
echo "<tr>";
for ($col = 0; $col < 5; $col ++) {
$rand = rand(1, 200);
$array[] = $rand; // <-- added code
echo "<td>", $rand, "</td>";
}
echo "</tr>";
}
echo "</table>";
$min = min($array); // <--- added code
$max = max($array); // <--- added code
?>
Check it out the max and min value of an aray in PHP using library function.
for($col = 0; $col < 5; $col ++) {
$rand[] = rand (1, 200);
}
echo $max = max($rand)."<br/>";
echo $min = min($rand)."<br/>";
print_r($rand);

Foreach multiple result set print in HTML table

I am trying to pull two results from 2 sql statements and print into HTML table.
but some how results are not coming correct.please hel me to resolve.
Below is code 2nd result is not printing correct results - duplicated results.
<?php
global $wpdb;
$result1=$wpdb->get_results("select post_name,id,cat from wp_posts where post_name like '%java%');
$result2=$wpdb->get_results("select post_name,id,cat from wp_posts where post_name like '%oracle%');
?>
<table id="table_id">
<thead>
<tr>
<th>JAVA</th>
<th>ORACLE</th>
</tr>
</thead>
<tbody>
<?php foreach($result1 as $rows1) { ?>
<?php foreach($result2 as $rows2) { ?>
<tr>
<td> <?php echo $rows1->post_name ; ?> </td>
<td> <?php echo $rows2->post_name ; ?> </td>
</tr>
<?php
}
?>
<?php
}
?>
global $wpdb;
$result1=$wpdb->get_results("SELECT post_name,id,cat FROM wp_posts WHERE post_name LIKE '%java%'");
$result2=$wpdb->get_results("SELECT post_name,id,cat FROM wp_posts WHERE post_name LIKE '%oracle%'");
After getting to objects , we put the required values in two arrays so that we can create a multi-dimensional array.
$result_one = array();
$result_two = array();
//putting values in array
foreach ($result1 as $result) {
$result_one[] = $result->post_name;
}
foreach ($result2 as $result) {
$result_two[] = $result->post_name;
}
//Creating a multi-dimensional array so that we can print two columns easily
$results = array(
$result_one,
$result_two,
);
//Initialising the variables to be used as counters and array indexes.
$i = 0; $j = 0; $k = 0; $p = 1;
//getting length of array
$array_length = count($result_one);
Now start two loops to fetch data from multi-dimensional array created.
In this case: To create the table properly we need values in this order:
$results[0][0], $results[1][0], $results[0][1], $results[1][1],
$results[0][2], $results[1][2] and so on.
So we have to create loops accordingly.
while ($i < 2) {
while ($j < $array_length) {
if (fmod($p,2)) echo '<tr>'; // So that <tr> will be printed only after two <td>
echo "<td>". $results[$i][$j]. "</td>";
if($i == 0) { $i = 1; } else { $i =0; } // Toggling values of $i from 0 to 1.
$k++;
if(fmod($k, 2) == 0){ $j ++; } // Increasing $j after 2 steps.
$p++;
if (fmod($p,2)) echo '</tr>';
}
$i ++;
}
If you need three columns:
Repeat steps one two and three so that you can create an array like this:
$results = array(
$result_one,
$result_two,
$result_three,
);
Change first while loop to
while ($i < 3)
And change the following statements as:
if (fmod($p,3)) echo '<tr>';
if($i == 0) { $i = 1; } elseif ($i == 1) {$i=2} else { $i = 0; }
if(fmod($k, 3) == 0){ $j ++; }
if (fmod($p,3)) echo '</tr>';
I hope you got better understanding now and can make the required changes yourself.
This seems complicated. But this should work. Please try.
Anyone please feel free to edit the while loop to make it simpler.
something i missed out for 3rd result array.please correct me.
$results = array(
$result_one,
$result_two,
$result_three,
);
$i = 0; $j = 0; $m = 0; $k = 0; $p = 1;
$array_length = count($result_one);
?>
<table id="table_id">
<thead>
<tr>
<th>ORACLE</th>
<th>JAVA</th>
<th>SAP</th>
</tr>
</thead>
<tbody>
<?php while ($i < 3) {
while ($j < $array_length) {
if (fmod($p,3)) echo '<tr>';
echo "<td>" . $results[$i][$j] . "</td>";
if($i == 0) { $i = 1; } elseif ($i == 1) {$i=2} else { $i = 0; }
$k++;
if(fmod($k, 3) == 0){ $j ++; }
$p++;
if (fmod($p,3)) echo '</tr>';
}
$i ++;
}
?>

How do I simplify this basic loop?

I have code which pretty much does this.....
//get the row info
$Row1 = $FullTable->find('div[class=ismPitchRow1]',0);
$Row2 = $FullTable->find('div[class=ismPitchRow2]',0);
$Row3 = $FullTable->find('div[class=ismPitchRow3]',0);
$Row4 = $FullTable->find('div[class=ismPitchRow4]',0);
$Row5 = $FullTable->find('div[class=ismPitchRow5]',0);
//Loop 5 times. One for each row on the pitch.
for ($i=1; $i<=5; $i++)
{
if ($i = 1) { echo $Row1; }
if ($i = 2) { echo $Row2; }
if ($i = 3) { echo $Row3; }
if ($i = 4) { echo $Row4; }
if ($i = 5) { echo $Row5; }
}
It works, but as you can see it's not very efficient and badly designed. How would I simplify this? I know there are much smaller ways that these kind of loops can be done.
Thanks.
use the great invention of arrays:
//get the row info
$Row[1] = $FullTable->find('div[class=ismPitchRow1]',0);
$Row[2] = $FullTable->find('div[class=ismPitchRow2]',0);
$Row[3] = $FullTable->find('div[class=ismPitchRow3]',0);
or, even more clever...
for ($i = 1; $i <= 5; $i++) {
$find = "div[class=ismPitchRow$i]";
$Row[$i] = $FullTable->find($find,0);
}
do the same for echoing:
for ($i = 1; $i <= 5; $i++) {
echo $Row[$i];
}
but why not do everything in 1 loop?
for ($i = 1; $i <= 5; $i++) {
$find = "div[class=ismPitchRow$i]";
echo $FullTable->find($find,0);
}
I would store $Row1 through $Row5 in an array and iterate through it with a foreach loop.
<?php
$YourArray = array();
array_push($YourArray,$FullTable->find('div[class=ismPitchRow1]',0),$FullTable->find('div[class=ismPitchRow2]',0),$FullTable->find('div[class=ismPitchRow3]',0),$FullTable->find('div[class=ismPitchRow4]',0),$FullTable->find('div[class=ismPitchRow5]',0));
foreach($YourArray as $row){
echo $row;
}
?>

Max, Min and sum Random Number php

Here's the code
<?php
echo "<table border=\"0\">";
for ($d = 1; $d <= $times;$d++ )
{
echo "<tr><td>";
echo rand(1,6), "\n";
echo "</td></tr>";
}
echo "</table>"; ?>
I'm trying to get the max,min and sum of the rand(1,6), "\n";
But i can't figure it out. And it's killing me.
$rands = array(); // rand() storage
for($d = 1; $d <= $times; $d++){
$rands[$d] = rand(1, 6); // store rands
}
var_dump($min = min($rands)); // min() of rands
var_dump($min = max($rands)); // max() of rands
^ see sample code.
(PS: I use [$d] as he has a 1-based increment and it may be needed for his further logic. This way the rands keys match his $d and can be easily accessed later on.)
You need to collect the random numbers in an array, too:
echo "<table border=\"0\">";
$rands = array();
#################
for ($d = 1; $d <= $times; $d++)
{
echo "<tr><td>";
echo $rands[] = rand(1,6), "\n";
###########
echo "</td></tr>";
}
echo "</table>"; ?>
Afterwards you can make use of max, min and array_sum (all these links come with nice examples).
As your code already shows you should start to differ between code that does data-processing and code that does the HTML output:
// handle the data
$randomNumbers = array();
foreach (range(1, $times) as $d)
{
$randomNumbers[$d] = rand(1,6);
}
// output the data
echo '<table border="0">';
foreach ($randomNumbers as $number) {
printf("<tr><td>%d</tr></td>", $number);
}
echo "</table>";
<?php
$min = 10;
$max = -1;
$sum = 0;
for ($d = 1; $d <= $times; $d++) {
$n = rand(1, 6);
if ($n < $min) $min = $n;
if ($n > $max) $max = $n;
$sum += $n;
}
echo $min . ' ' . $max . ' ' . $sum . '<br/>';
?>
$sum=0;
for ($d = 1; $d <= $times;$d++ ) {
echo "<tr><td>";
$r=rand(1,6);
$sum +=$r;
echo "$r, \n";
echo "</td></tr>";
if ($d==1) { $min=$r; $max=$r; }
if ($r>$max) $max=$r;
if ($r<$min) $min=$r;
}
// do something with $min, $max and $sum;
<?php
$total = 0;
echo "<table border=\"0\">";
for ($d = 1; $d <= $times;$d++ )
{
$rand = rand(1,6);
$total += $rand;
$array[] = $rand;
echo "<tr><td>";
echo $rand, "\n";
echo "</td></tr>";
}
echo "</table>"; ?>
echo $total;
echo min($array);
echo max($array);

Print Terms in Node in Multiple Columns Sorted in Downward Order

I have approximately 20 content-taxonomy check boxes from one field ("features"). The checked terms display in node-example.tpl.php. I am trying to show these content-taxonomy terms in two columns displayed/sorted in a downward order instead of across.
I am trying to cobble two bits of code to accomplish this...but my php skills are not yet up to the challenge. I can't get all of the array values generated in the foreach loop to be recognized by the second section of code.
The code below was taken (and modified) from the following sources:
http://drupal.org/node/312812
roscripts.com/PHP_display_data_on_columns-127.html
I am trying to use the following code in my node-example.tpl.php file.
<?php
echo '<table>';
foreach ($node->field_features as $delta => $value){
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
}
// Default # of Columns
$numcols = 2;
// Number of Items
$numitems = count($term_name);
// Number of Rows
$numrows = ceil($numitems/$numcols);
for ($row=1; $row <= $numrows; $row++)
{
$cell = 0;
echo ' <tr>'."\n";
for ($col=1; $col <= $numcols; $col++)
{
echo ' <td>'."\n";
if ($col===1)
{
$cell += $row;
print $term_name[$cell - 1];
}
else {
$cell += $numrows;
print $term_name[$cell - 1];
}
echo ' </td>'."\n";
}
echo ' </tr>'."\n";
}
echo '</table>';
?>
Ok, I got this to work using the answer to another foreach-loop question/answer on this site.
Declare the $items array outside the
loop and use $items[] to add items to
the array.
This is the final code that does exactly what I wanted.
<?php
echo '<table>';
$items = array();
foreach ($node->field_features as $delta => $value)
{
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
$items[] = $term_name;
}
// Default # of Columns
$numcols = 2;
// Number of Items
$numitems = count($items);//print $numitems;
// Number of Rows
$numrows = ceil($numitems/$numcols);//print $numrows;
for ($row=1; $row <= $numrows; $row++)
{
$cell = 0;
echo ' <tr>'."\n";
for ($col=1; $col <= $numcols; $col++)
{
echo ' <td>'."\n";
if ($col===1)
{
$cell += $row;
print $items[$cell - 1];
}
else {
$cell += $numrows;
print $items[$cell - 1];
}
echo ' </td>'."\n";
}
echo ' </tr>'."\n";
}
echo '</table>';
?>
You can use theme('table', $headers, $rows) to render your table using the theme engine.
// Default # of Columns
$numcols = 2;
$rows = array();
$cell_count = 0;
foreach ($node->field_features as $delta => $value) {
$term = taxonomy_get_term($node->field_features[$delta]['value']);
$term_name = check_plain($term->name);
$cell_count += 1;
$row_index = floor($cell_count / $numcols);
$rows[$row_index][] = $term_name;
}
print theme('table', array(), $rows);

Categories