why the function echo one result?
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
foreach ($terms as $term){
return $term->name;
}
}
When i invoke the function echo blog_getta开发者_开发百科g()
. there is only one result. but when i change the function retrun to echo. then blog_gettag()
.it prints ok. why?
That's because you're only returning one item. You're returning as soon as it finds the first item.
A solution would be to return an array with all tag names, like this:
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
$items = array(); // Array holding return values
foreach ($terms as $term){
$items[] = $term->name;
}
return $items;
}
You can then iterate over all tags like this:
$tags = blog_gettag();
foreach($tags as $tag) {
echo $tag;
}
return
will stop running the function any further. It implies your function has done what it has to do. If you want it to return all tags, you should change something:
function blog_gettag(){
$aTerms = array();
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
foreach ($terms as $term){
$aTerms[] = $term->name ;
}
return $aTerms;
}
return will end the loop,
http://php.net/manual/en/function.return.php
Functions will only execute until something needs to be returned. Return essentially means "This is the output of the method" and then it stops doing everything.
In your example you're returning the first row and then the function exists. Workaround by producing an array:
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
$names = array();
foreach ($terms as $term){
$names[] = $term->name;
}
return $names;
}
a function can return only one value in php. if you want complete array then first save all result in an array & then return that array
When you return
the function yields control to the caller, so you will exit the loop after the first iteration through the loop.
精彩评论