Home > Software design >  php - how to generate new <tr> after fourth iteration from 2 arrays and display them in altern
php - how to generate new <tr> after fourth iteration from 2 arrays and display them in altern

Time:12-11

i have 2 arrays:

$arr1= ['A','B','C'];

$arr2=[1, 2, 3];

what i want to achieve is something like this:

-----------------
| A | A | A | A |
-----------------
| 1 | 1 | 1 | 1 |
-----------------
| B | B | B | B |
-----------------
| 2 | 2 | 2 | 2 |
-----------------
| C | C | C | C |
-----------------
| 3 | 3 | 3 | 3 |
-----------------

and this is what i've tried: `

<?php
$arr1= ['A','B','C'];
$arr2=[1, 2, 3];
$combine = array_combine($arr1, $arr2);

echo "<table>\n";
foreach ( $combine as $i => $a) {
    echo "<tr>\n";
    for ($j=0; $j < 4 ; $j  ) { 
  if ( $a % 4 == 0) {
    echo "</tr>\n  <tr>\n";
  }
  echo "<th>$i</th>\n";
  echo "<td>$a</td>\n";
  }
  echo "</tr>\n";
}

echo "</table>\n";

?>

`

the result isn't like what i'm expecting.

enter image description here

any help will be greatly appreciated.

CodePudding user response:

No need of nested for loops or any % 4. Access the value from the second array using the key from the foreach iteration of the first array since both arrays are symmetrical in size and type. Use str_repeat 4 times to print the value 4 times as required.

<?php

$arr1 = ['a','b','c'];
$arr2 = [1, 2, 3];

echo "<table>";
foreach ( $arr1 as $key => $value) {
  echo "<tr>" , str_repeat("<td>$value</td>", 4) , "</tr>";
  echo "<tr>" , str_repeat("<td>$arr2[$key]</td>", 4) , "</tr>";
}

echo "</table>";

Online Demo

  • Related