问题
Pretty new to all this, but here i go...
I need to make 2 patterns using a table (without borders) and for-loops:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
I did work this one out with (probably not the easiest way tho, but it works):
<table>
<b>Patroon I</b>
<?php
$pattern = array();
for($pyramid = 1; $pyramid <=6; $pyramid++){
$pattern[$pyramid] = $pyramid;
echo "<tr>
<td class='td1'>" . $pattern[1] . "</td>";
if(array_key_exists(2, $pattern)){
echo "<td class='td1'>" . $pattern[2] . "</td>";
}
if(array_key_exists(3, $pattern)){
echo "<td class='td1'>" . $pattern[3] . "</td>";
}
if(array_key_exists(4, $pattern)){
echo "<td class='td1'>" . $pattern[4] . "</td>";
}
if(array_key_exists(5, $pattern)){
echo "<td class='td1'>" . $pattern[5] . "</td>";
}
if(array_key_exists(6, $pattern)){
echo "<td class='td1'>" . $pattern[6] . "</td>";
}
echo "</tr>";
}
?>
</table>
and the other pattern
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Which I can't seem to figure out.
I tried to turn the previous code around, tried rsort($pattern), tried a lot of IF-statements, and now im stuck :S
Anyone has a hint for me?
Thanks!
回答1:
You don't need any array or fancy function, just two nested for loops.
<table>
<?php
// 1
// 1 2
// 1 2 3
// ...
$rows = 6;
for ($row = 1; $row <= $rows; $row++) {
echo "<tr>";
for ($col = 1; $col <= $row; $col++) {
echo "<td class='td1'>" . $col . "</td>";
}
echo "</tr>";
}
?>
</table>
<br />
<table>
<?php
// 1 2 3 4 5 6
// 1 2 3 4 5
// 1 2 3 4
// ...
$rows = 6;
for ($row = $rows; $row > 0; $row--) {
echo "<tr>";
for ($col = 1; $col <= $row; $col++) {
echo "<td class='td1'>" . $col . "</td>";
}
echo "</tr>";
}
?>
</table>
Add the following code before the closing row tag for balanced table rows.
if ($span = $rows - $row)
echo "<td colspan='$span'></td>";
回答2:
Try to 2 loops for getting output. Dont use array
<b>Patroon I</b>
<br>
<?php
for($pyramid = 1; $pyramid <=6; $pyramid++){
for($i=1;$i<=$pyramid;$i++)
{
echo $i." ";
}
echo "<br>";
}
?>
<b>Patroon II</b>
<br>
<?php
for($pyramid = 6; $pyramid >=1; $pyramid--){
for($i=1;$i<=$pyramid;$i++)
{
echo $i." ";
}
echo "<br>";
}
?>
回答3:
<?php
$pattern=array(1,2,3,4,5,6);
//var_dump($pattern);
for($pyramid1 = 6; $pyramid1 >=0; $pyramid1--){
echo "<tr>
<td class='td1'>";
for($i = 0; $i <=$pyramid1; $i++){
echo $pattern[$i] ;
}
echo "</td>";
echo "</tr>";
}
?>
</table>
来源:https://stackoverflow.com/questions/46197415/pattern-output-stuck