2015-12-20 47 views
0

我需要在php中繪製一個金字塔,只有3個級別將在那裏,並將在頁面的中心,我嘗試了很多,但無法複製輸出 這是代碼我在網上找到並修改了一下(想到在基本結構到位後再進行編號部分)需要在PHP中繪製金字塔

一個方面說明:試圖將其生成爲HTML表格,以便它保持一致。

<?php 
$height = 3; 

echo "<div>"; 
for($i=1;$i<=$height;$i++){ 
    for($t = 1;$t <= $height-$i;$t++) 
    { 
    echo "&nbsp;&nbsp;"; 
    } 
    echo "<center>"; 
    for($j=1;$j<=$i;$j++) 
    { 
    // use &nbsp; here to procude space after each asterix 
    for ($x=0; $x < 3; $x++) { 
     echo "*&nbsp;&nbsp;"; 
    } 
    } 
    echo "<br />"; 
} 
echo "</center>"; 
echo "</div>"; 
?> 

下面是我想實現:

The pyramid I need

+0

你能否解釋一下是對我來說是高度靜態?爲什麼第二行4號碼?總數是21? –

+0

是在一個時間僅顯示3個水平或高度= 3,因爲 高度= 3總21. 基本上其 級別0 = 4^0 = 1 級別1 = 4^1 = 4 級別2 = 4^2 = 16 –

回答

1

讓我們分開的金字塔建築和印刷:

<?php 

$pyramid = []; 
$levels_count = 3; // height of the pyramid 
$parts_count = 4; // number of subdividing parts 
$index = 1; // starting index to numerate vertices 
$level = 0; 

$columns_count = pow($parts_count, $levels_count - 1); 
for ($level = 0; $level < $levels_count; $level++) { 
    $level_items_count = pow($parts_count, $level); 
    $pyramid[$level] = [ 
    'colspan' => $columns_count/$level_items_count, 
    'items' => range($index, $index + $level_items_count - 1) 
    ]; 
    $index += $level_items_count; 
} 

// The following code prints the prepared pyramid data 
?> 
<style> 
td { 
    text-align: center; 
    background-color: #ccc; 
} 
</style> 
<table> 
<?php foreach ($pyramid as $row): ?> 
    <tr> 
    <?php foreach ($row['items'] as $col): ?> 
    <td colspan="<?= $row['colspan']; ?>"><?= $col; ?></td> 
    <?php endforeach; ?> 
    </tr> 
<?php endforeach; ?> 
</table>