Foreach in middle of return statement
I'm working on a tagging system for an image site, and I have:
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>';
And then farther down in 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;
}
And the problem I have is the foreach
inside the return
statement of the format function. I'm really confused as to how to make this work. How does one go about a function inside a return?
Put the foreach earlier in your code:
$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>';
You could use output buffering in your function like this:
function formatImage($url, $description, $tags){
//...
ob_start();
?><div etc...
...
<?php
foreach (...) {
?><a href="...">...<?php
}
$output .= ob_get_contents();
ob_end_clean();
return $output;
}
This could affect any existing output (depending on your application is set up) so you would want to call formatImage()
before anything is output, possibly by wrapping the page in some kind of View container (like how an MVC framework like CakePHP or CodeIgniter works).
精彩评论