How to collect functions results into one array and return this array?
My php function looks like that
function generateTour ($lang, $db)
{
echo '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0) echo '<tr>';
echo '<td width="33%">
<div class="tour_item" style="bac开发者_运维技巧kground-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">';
echo '</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1) echo '</td></tr>';
else if($i%3==0) echo '</td></tr><tr>';
$i++;
}
echo '</table>';
}
As you see it echoes result line by line. Not all at once. I want to collect all variables to one array and return this array. Is it possible? how to do it?
Please don't post your ideas about security holes .. etc. I'm filtering $title, $txt
varibales against sql injections. (i have array for of possible field names. My filter function checks theese variables' values every time. )
$data = array();
while ($row = $result->fetchObject()) {
$data[] = $row;
}
Is the absolutely most basic method of cacheing a result set in an array. You'd just modify this to store your generated html instead.
Try this:
function generateTour ($lang, $db)
{
$output = '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0)
{
$output .= '<tr>';
}
$output .= '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">
</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1)
{
$output .= '</td></tr>';
}
else if($i%3==0)
{
$output .= '</td></tr><tr>';
}
$i++;
}
$output .= '</table>';
return $output;
}
Edit: Now it's easier to read the code. This solution put all content in one variable. You don't need a array.
You can use ob_start()
and ob_get_clean()
to buffer all output into a variable, then output that variable, like this:
ob_start();
print "Hello"; // Prints to buffer instead of screen
$out = ob_get_clean(); // Contains: Hello
echo $out; // Prints: Hello
精彩评论