2016-03-16 71 views
0

在我所有的多年的创作PHP的,我从来没有碰到过一个场合中,我需要把for循环一个标准的PHP变量中。把循环放入变量中?

原因是:我需要通过JSON请求来传递这个变量。

见下面我当前的代码。

什么我在这里做的是写一个脚本来生成基于用户需求的标准的HTML表(行&列e.g数)。我需要将所有这些HTML放入一个变量中,并通过JSON请求传递该变量,然后解码并显示给用户。

任何意见/建议/技巧将是一个巨大的帮助。

<?php 
$trows = 5; 
$tcolumns = 7; 

echo "<table class='table table-striped table-bordered'>"; 
echo "<thead>"; 
echo "<tr>"; 
for ($th = 0; $th < $tcolumns; $th++){echo '<th>[HEADER]</th>'; 
}; 
echo "</tr>"; 
echo "</thead>"; 
echo "<tbody>"; 
    for ($tr = 0; $tr < $trows; $tr++){ echo '<tr>'; 
     for ($td = 0; $td < $tcolumns; $td++){echo '<td>[CONTENT]</td>'; 
     }; 
     echo "</tr>"; 
    } 
echo "</tbody>"; 
echo "</table>"; 
?> 
+0

你的输出分配给直接呼应它的变量instad? – maxhb

+0

@maxhb介意说明一下吗? –

回答

1
<?php 
$trows = 5; 
$tcolumns = 7; 
$result = ""; 
$result .= "<table class='table table-striped table-bordered'>"; 
$result .= "<thead>"; 
$result .= "<tr>"; 
for ($th = 0; $th < $tcolumns; $th++){$result .= '<th>[HEADER]</th>'; 
}; 
$result .= "</tr>"; 
$result .= "</thead>"; 
$result .= "<tbody>"; 
    for ($tr = 0; $tr < $trows; $tr++){$result .= '<tr>'; 
     for ($td = 0; $td < $tcolumns; $td++){$result .= '<td>[CONTENT]</td>'; 
     }; 
     $result .= "</tr>"; 
    } 
$result .= "</tbody>"; 
$result .= "</table>"; 
?> 
+0

啊,是的,这就像一个魅力。谢谢你,先生。 –

-1

使用输出缓冲:

// Start output buffering 
ob_start(); 

/* 
    Your code here 
*/ 

// Fetch buffered output and save to variable 
$content = ob_get_contents(); 

// End output buffering, flush buffer. This outputs the buffer content 
ob_end_clean(); 

// If you don't want the buffer to be output use this 
// ob_end_clean(); 
1

创建一个变量,说$output,到HTML表存储在
完成建立你可以做任何你选择的表之后。用它。打印出来,用它在另一个变量来建立一个json对象。

见下

$output = "<table class='table table-striped table-bordered'>"; 
$output .= "<thead>"; 
$output .= "<tr>"; 

for ($th = 0; $th < $tcolumns; $th++){ 
    $output .= '<th>[HEADER]</th>'; 
}; 

$output .= "</tr>"; 
$output .= "</thead>"; 
$output .= "<tbody>"; 

for ($tr = 0; $tr < $trows; $tr++){ 

    $output .= '<tr>'; 

    for ($td = 0; $td < $tcolumns; $td++){ 
     $output .= '<td>[CONTENT]</td>'; 
    }; 

    $output .= "</tr>"; 
} 

$output .= "</tbody>"; 
$output .= "</table>"; 

echo $output; 
+0

谢谢,亚历克斯。然而Aju首先发布,所以我必须给他绿色支票。无论如何感谢朋友。 –