Generating HTML table from PHP array - php

I don't understand this. I need to solve seemingly simple problem, and yet it's beyond my logic. I need to write a function: table_columns($input, $cols) which would output a table(example):
$input = array('apple', 'orange', 'monkey', 'potato', 'cheese', 'badger', 'turnip');
$cols = 2;
Expected output:
<table>
<tr>
<td>apple</td>
<td>cheese</td>
</tr>
<tr>
<td>orange</td>
<td>badger</td>
</tr>
<tr>
<td>monkey</td>
<td>turnip</td>
</tr>
<tr>
<td>potato</td>
<td></td>
</tr>
</table>

Think about it like this. Say you have an array of items like this:
a, b, c, d, e, f, g, h, i, j, k
With columns set to 2, you'd need to render them in this order:
a g
b h 0 6 1 7 2 8 3 9 4 10 5
c i ---> a g b h c i d j e k f
d j
e k
f
With three columns:
a e i
b f j 0 4 8 1 5 9 2 6 10 3 7
c g k ---> a e i b f j c g k d h
d h
So, roughly:
function cells ($input, $cols) {
$num = count($input);
$perColumn = ceil($num / $cols);
for ($i = 0; $i < $perColumn; $i++) {
echo "<tr>";
for ($j = 0; $j < $cols; $j++) {
// you'll need to put a check to see you haven't gone past the
// end of the array here...
echo "<td>" . $input[$j * $perColumn + $i] . "</td>";
}
echo "</tr>";
}
}

$input = array_chunk($input, $cols);
$html = '<table>';
foreach($input as $tr){
html .= '<tr>';
for($i = 0; $i < $cols; $i++) $html .= '<td>'.(isset($tr[$i]) ? $tr[$i] : '').'</td>';
$html .= '</tr>';
}
$html .= '</table>';

Try this function:
function table_columns($input, $cols)
{
int $i = 0;
echo "<table><tr>";
foreach ( $input as $cell )
{
echo "<td>".$cell."</td>";
$i++;
if($i == $cols)
{
$i = 0;
echo "</tr><tr>";
}
}
echo "</tr></table>";
}
I hope it solves your problem.
[EDIT: Fixed the mistakes, was in a hurry]

Related

PHP array_rand weird behaviour

I was trying to create a simple password generator and noted that array_rand() returns the same results. Here is the code:
<?php
function generatePass() {
$password = '';
$a = explode(' ', 'q w e r t y u i o p a s d f g h j k l z x c v b n m');
for($i=0; $i < rand(1,200); $i++) {
$password .= $a[array_rand($a)];
}
return $password;
}
$r = 0;
while ($r <= 10000) { #generating 10 000 passwords
$total[] = generatePass();
$r++;
}
echo '<pre>';
print_r($total);
echo '</pre>';
?>
The $total array basically contains the same results repeated over and over again; if I refresh the page, only the order of elements changes, and not their values.
The question is: is this an expected behaviour or am I doing something wrong?
Thak you for your attention.
Reseed the random number generator with srand() just prior to calling array_rand.
srand();
$password .= $a[array_rand($a)];
I think it should be your PHP version. I just copied your code into my localhost server and it worked fine. I'm using PHP 5.5.9-1ubuntu4.7, you should try it or a newer version.
By the way, if you can't update your PHP version, use this modified version of your code:
<?php
function generatePass() {
$password = '';
// Put all letters into an array.
$letters = array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
for($i=0; $i < rand(1,200); $i++) {
// Select a random letter with rand() command inside the brackets of the array.
$password .= $letters[rand(0,25)];
}
return $password;
}
$r = 0;
while ($r <= 10000) { #generating 10 000 passwords
$total[] = generatePass();
$r++;
}
echo '<pre>';
print_r($total);
echo '</pre>';
?>
Seeding the random generator isn't needed since version 4.2.0
Try using mt_rand() for a better generation.
http://php.net/manual/en/function.mt-rand.php
Edit:
I think you actually want
$a = explode(' ', 'q w e r t y u i o p a s d f g h j k l z x c v b n m');
$end = mt_rand(1,200);
$password = '';
for($i=0; $i < $end; $i++) {
$password .= $a[array_rand($a)];
}
I took the time for you and wrote the generator.
I got it to generate 10000 unique passwords and code is efficient:
<?php
function generatePass() {
$password = '';
$lib = 'q w e r t y u i o p a s d f g h j k l z x c v b n m';
$a = explode(' ', $lib);
//remove random char
for($i=0; $i < mt_rand(1,49); $i++) {
shuffle($a);
//get Random Char
$password .= $a[mt_rand(0,count($a)-1)];
}
return $password;
}
$len = 10000; // total number of numbers
$range = array();
foreach(range(0, $len - 1) as $i){
while(in_array($num = generatePass(), $range)){}
$range[] = $num;
}
echo '<pre>';
print_r($range);
echo '</pre>';

Trying to display a random generated string on my page

I'm trying to display a random generated string on my page (php), but I have absolutely no idea how to do this.
I only want the following letters and digits to be used:
B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9
In the following format:
XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
Can anyone help me out, and give me a script which I can put on my page? Help would be really appreciated!
I tried this but it's not even displaying on my page for some odd reason.
$tokens = 'BCDFGHJKMPQRTVWXYZ2346789';
$serial = '';
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, 35)];
}
if ($i < 3) {
$serial .= '-';
}
}
echo $serial;
You were almost there. Here's a few fixes to your code;
<?php
$tokens = 'BCDFGHJKMPQRTVWXYZ2346789';
$serial = '';
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, strlen($tokens) - 1)];
}
if ($i < 4) {
$serial .= '-';
}
}
echo $serial;
?>
I can't say for sure why your page isn't showing, but in your original code you were missing <?php at the top of the page.
Edit: Here's a quick explanation of some of the changes I made to your code.
Your code had rand(0, 35). But since you may change the characters in $tokens in the future, it's better to simply calculate the length of the $tokens using strlen($tokens) - 1 (the -1 being important because strlen() starts counting at 1, whereas $tokens[INDEX] starts counting at 0).
Your code had if ($i < 3), but you actually want four dashes, so I changed it to if ($i < 4).
<?php
$charsPerGroup = 5;
$groups = 5;
$groupDelimiter = '-';
$tokens = explode(' ', 'B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9'); // from your question, format this however you want
$tokens = array_flip($tokens);
$resultArray = array();
for($i=0;$i<$groups;$i++) {
$resultArray[] = join(array_rand($tokens, $charsPerGroup));
}
echo join($groupDelimiter, $resultArray);
<?php
$enters = explode(' ', "B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9");
$entry = rand(0,count($enters)-1);
echo $enters[$entry];
$output = "";
for($i=1; $i++; $i<=25) {
$entry = rand(0,count($enters)-1);
$output .= $enters[$entry] . ($i % 5 == 0 && $i < 25 ? '-' : '' );
}
echo $output;
?>

How to find contiguous words in array

ok, this is driving me insane, the solution must be easy but I've hit the proverbial wall,
here it is:
suppose I have this Array: a, b, c, d
I want to find all the contiguous letters in the array without mixing them, such as:
a b c d
a b c
a b
b c d
b c
c d
I've done many tests, but for some reason I just can't get it right. Any hint would be greatly appreciated.
$arr = Array('a', 'b', 'c', 'd');
for ($i = 0; $i < count($arr); $i++) {
$s = '';
for ($j = $i; $j < count($arr); $j++) {
$s = $s . $arr[$j];
if (strlen($s) > 1) {
echo $s.' ';
}
}
}
OUTPUT:
ab abc abcd bc bcd cd

Non-recursive dynamic binary tree with PHP

I try to create a binary tree as html-table which is not recursive build. The order of the fields should be like this:
C1 C2 C3
7
3
8
1
9
4
10
11
5
12
2
13
6
14
C1 stands for col 1, C2 for col2 etc.
The following code creates a table in a recursive way, but this is not what I want!
<?php
$cols = 4;
$counter = 0;
$lines = pow(2,$cols);
echo '<table border=1 style="border:1px solid black;"> ';
for($i = 0; $i < $lines; $i++){
echo '<tr>';
for($j = 0; $j < $cols; $j++){
$rowspan = $lines/pow(2,$j+1);
if(0 === $i%$rowspan) {
$counter++;
echo '<td rowspan='.$rowspan.'>'.$counter;
}
}
}
echo '</table>';
?>
I hope someone could give me a hint how to solve this problem.
Used this expression to calculate the row's values: ($i / $rowspan + pow(2,$j+1) - 1) wherein $i / $rowspan is the number of the row in the current level starting with 0 for the first row and pow(2,$j+1) - 1 is the level's first value, i.e. 7 for the third level.
$cols = 4;
$lines = pow(2,$cols);
echo '<table border=1 style="border:1px solid black;">';
for($i = 0; $i < $lines; $i++){
echo '<tr>';
for($j = 0; $j < $cols; $j++){
$rowspan = $lines/pow(2,$j+1);
if(0 === $i%$rowspan) {
echo "<td rowspan='$rowspan'>".
($i/$rowspan + pow(2,$j+1)-1).
"</td>";
}
}
}
echo '</table>';
Outputs your desired result. Hope your teacher won't hate me now! ;-)
You can alternativly use ($i/$lines + 1 ) * pow(2,$j+1) - 1 for the row's value, if you don't want to depend on $rowspan.

Change for in PHP with table

<table><tr>
<?php
for($i=0;$i<15;$i++) {
if($i%5 == 0) {echo '</tr> <tr>';}
?><td><?php echo $i ?></td>
<?php
}?>
</tr>
</table>
this generate:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
how can I make:
0 3 6 9 12
1 4 7 10 13
2 5 8 11 14
?
You need a nested loop
<table>
<?php
$rows = 3;
for($i=0 ; $i < $rows ; $i++ ) {
echo "<tr>";
for( $j = 0 ; $j < 5 ; $j++ ) {
echo "<td>" . ($j * $rows + $i) . "</td>";
}
echo "</tr>";
}
?>
</table>
I tried to make the variable names descriptive:
<table>
<?php
// Set the number of rows, cols, and starting number here:
$number_rows = 3;
$number_cols = 5;
$starting_num = 0;
// You can use foreach w arrays... much easier
$rows = range(0,$number_rows - 1);
$cols = range(0,$number_cols - 1);
foreach($rows as $one_row) {
?>
<tr>
<?php
foreach($cols as $one_col) {
// Do the calculation
echo "<td>" .
($starting_num + $one_col + ( max($rows) * $one_col ) + $one_row) .
"</td>";
}
?>
</tr>
<?php
}
?>
</table>
Working example like in the OP.
Now let's say you want to go from (1300-1431), then you start at 1300 and want a 4 x 8.
$number_rows = 8;
$number_cols = 4;
$starting_num = 1300;
Like this.
There are two "tricks."
The first is using range() to quickly define an array integers. I find arrays more pleasant to work with than raw numbers, since arrays can be worked on with the intuitive construct of foreach().
The second is figuring out how to know what number to print if you have the column, row, and starting, number. It's simplest to figure out the numbers for the first row and go from there. Let's number the rows and cols from 0. So col:0 row:0 will be the starting number. Col:1 Row:0, the number to the right, will just be the starting number + one (the column number) + the number of rows less one (easiest to see by looking at the matrix of number), and the number of rows less one is the maximum number in the rows array. So for the first row we have:
$starting_num + $one_col + ( max($rows) * $one_col )
then all we just add the row number to take that into account, and we've got it all:
$starting_num + $one_col + ( max($rows) * $one_col ) + $one_row
Tested example with given start and end:
<table>
<?php
$start = 1300;
$end = 1432;
$n = $end - $start + 1;
$cols = 5;
$rows = ceil($n / $cols);
for($i=0 ; $i < $rows ; $i++ ) {
echo "<tr>";
for( $j = 0 ; $j < $cols ; $j++ ) {
$val = $j * $rows + $i;
echo "<td>";
echo ($val < $n) ? $val + $start : ' ';
echo "</td>";
}
echo "</tr>";
}
?>
</table>

Categories