我正在为图像网站开发标记系统,我有:
function formatImage($url, $description, $tags){
if(empty($description)){
$description = "<i>No description avaliable.</i>";
}
$tags = array("One", "Two");
$added = "May 23, 2011";
return '
<div id="single" class="image">
<div id="image">
<img src="'.$url.'" />
</div>
</div>
<div id="meta">
<dl>
<dt>Description</dt>
<dd>'.$description.'</dd>
<dt>Added on</dt>
<dd>'.$added.'</dd>
<dt>Tagged</dt>
<dd id="tags">'.
foreach($tags as $tag){
return '<a href="/tagged/'.$tag.'">'.$tag.'</a>;
}
.'
</dd>
</dl>
</div>';
然后在functions.php中进一步向下:
function pullImage($id){
dbCon();
$sql = "SELECT * FROM images WHERE id='$id'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$url = $row['url'];
$description = $row['description'];
//Tags
$sql = "SELECT * FROM tags WHERE itemid='$id'";
$result = mysql_query($sql);
$tags = array();
while($row = mysql_fetch_assoc($result)){
array_push($tags, $row['tag']);
}
//$tags = $tags;
$image = formatImage($url, $description, $tags);
echo $image;
}
我遇到的问题是格式函数的foreach
语句中的return
。我真的很困惑如何使这项工作。如何在回报中使用函数?
答案 0 :(得分:3)
将foreach更早地放入代码中:
$tagList = array();
foreach($tags as $tag){
$tagList[] = '<a href="/tagged/'.$tag.'">'.$tag.'</a>';
}
return '
<div id="single" class="image">
<div id="image">
<img src="'.$url.'" />
</div>
</div>
<div id="meta">
<dl>
<dt>Description</dt>
<dd>'.$description.'</dd>
<dt>Added on</dt>
<dd>'.$added.'</dd>
<dt>Tagged</dt>
<dd id="tags">'.implode(', ', $tagList).'</dd>
</dl>
</div>';
答案 1 :(得分:0)
您可以在函数中使用输出缓冲:
function formatImage($url, $description, $tags){
//...
ob_start();
?><div etc...
...
<?php
foreach (...) {
?><a href="...">...<?php
}
$output .= ob_get_contents();
ob_end_clean();
return $output;
}
这可能会影响任何现有输出(取决于您的应用程序设置),因此您可能希望在输出任何内容之前调用formatImage()
,可能是通过将页面包装在某种View容器中(就像MVC一样)像CakePHP或CodeIgniter这样的框架。)