如何从函数返回变量

时间:2012-03-03 15:29:19

标签: php function variables

这可能是直截了当但我失去了

我有这段代码

$query = "
SELECT torrents.id, 
       torrents.anon, 
       torrents.announce, 
       torrents.parentcat, 
       torrents.category, 
       torrents.vip, 
       torrents.`4ever`, 
       torrents.leechers, 
       torrents.nfo, 
       torrents.seeders, 
       torrents.name, 
       torrents.times_completed, 
       torrents.`size`, 
       torrents.added, 
       torrents.comments, 
       torrents.numfiles, 
       torrents.filename, 
       torrents.owner, 
       torrents.safe, 
       torrents.external, 
       torrents.freeleech, 
       categories_parent.cat_parent_name, 
       categories_parent.image_parent, 
       categories.name                                    AS cat_name, 
       categories.image                                   AS cat_pic, 
       users.username, 
       users.privacy, 
       Round(torrents.ratingsum / torrents.numratings, 1) AS rating 
FROM   torrents 
       LEFT JOIN categories 
         ON category = categories.id 
       LEFT JOIN categories_parent 
         ON parentcat = categories_parent.cat_parent_id 
       LEFT JOIN users 
         ON torrents.owner = users.id 
WHERE  visible = 'yes' 
       AND safe = 'yes' 
       AND banned = 'no' 
ORDER  BY id DESC 
LIMIT  5 ";
$res = SQL_Query_exec($query);
if (mysql_num_rows($res)) {
    torrenttable1($res);

现在我的函数代码生成一个表,如果我想要一个函数的值,即行[id]在我的原始代码中使用我如何从我的函数发回它以及如何将它拿起以便我可以继续使用该值。

function torrenttable($res) {
global $site_config, $CURUSER, $THEME, $LANGUAGE;  //Define globals

if ($site_config["MEMBERSONLY_WAIT"] && $site_config["MEMBERSONLY"] && in_array($CURUSER["class"], explode(",",$site_config["WAIT_CLASS"]))) {

$wait = $site_config["WAITA"];
}

// Columns
$cols = explode(",", $site_config["torrenttable_columns"]);
$cols = array_map("strtolower", $cols);
$cols = array_map("trim", $cols);
$colspan = count($cols);
// End

// Expanding Area
$expandrows = array();
if (!empty($site_config["torrenttable_expand"])) {
    $expandrows = explode(",", $site_config["torrenttable_expand"]);
    $expandrows = array_map("strtolower", $expandrows);
    $expandrows = array_map("trim", $expandrows);
}
// End



while ($row = mysql_fetch_assoc($res)) {
    $id = $row["id"];

    print("<li><div id=row>");

$x = 1;

foreach ($cols as $col) {
    switch ($col) {
        case 'category':
            print("<div id=left>");
            if (!empty($row["cat_name"])) {
                print("<a href=\"torrents-search.php?cat=" . $row["category"] . "\">");

                if (!empty($row["cat_pic"]) && $row["cat_pic"] != "")
                    print("<img border=\"0\"src=\"" . $site_config['SITEURL'] . "/images/categories/" . $row["cat_pic"] . "\" alt=\"" . $row["cat_name"] . "\" />");
                else
                    print("$row[cat_name]");
                print("</a>");
            } else
                print("-");
            print("</div>\n");
        break;
        //km added for parent picture
        case 'parent':
            print("<div id=left>");
            if (!empty($row["cat_parent_name"])) {
                //print("<a href=\"torrents-details.php?id=$id&amp;hit=1\">");
                print("<a href=\"torrents-search.php?cat1=" . $row["parentcat"] . "\">");
                                    if (!empty($row["image_parent"]) && $row["image_parent"] != "")
                    print("<img border=\"0\"src=\"" . $site_config['SITEURL'] . "/images/categories/" . $row["image_parent"] . "\" alt=\"" . $row["cat_parent_name"] . "\" />");
                else
                    print("$row[cat_parent_name]");
                print("</a>");
            } else
                print("-");
            print("</div>\n");
        break;

        //kn end for parent picture//


        case 'name':
            $char1 = 60; //cut name length 
            $smallname = htmlspecialchars(CutName($row["name"], $char1));
            $dispname = "<b>".$smallname."&nbsp;</b>";
            $time = date('jS M Y, g:ia', utc_to_tz_time($row['added']));

            //balloon mod

          $bimg = @mysql_fetch_array(@mysql_query("SELECT image1 FROM torrents WHERE id=$id"));
         $balon =($bimg["image1"] ? "$site_config[SITEURL]/uploads/images/" . htmlspecialchars($bimg["image1"]) : "images/nocover.jpg");

                 print("<div id=left>".(count($expandrows)?"<a href=\"java script: klappe_torrent('t".$row['id']."')\"><img border=\"0\" src=\"".$site_config["SITEURL"]."/images/plus.gif\" id=\"pict".$row['id']."\" alt=\"Show/Hide\" class=\"showthecross\"></a>":"")."&nbsp;<a href=\"torrents-details.php?id=$id&amp;hit=1\" onMouseover=\"ddrivetip('<img border=0 width=120 src=$balon>')\"; onMouseout=\"hideddrivetip()\">$dispname</a><br><font color=grey><small>&nbsp;Added:&nbsp; ".$time."</font></small></div>");               
            //end balloon mod




        //  print("<td class='ttable_col$x' nowrap='nowrap'>".(count($expandrows)?"<a href=\"javascript: klappe_torrent('t".$row['id']."')\"><img border=\"0\" src=\"".$site_config["SITEURL"]."/images/plus.gif\" id=\"pict".$row['id']."\" alt=\"Show/Hide\" class=\"showthecross\" /></a>":"")."&nbsp;<a title=\"".$row["name"]."\" href=\"torrents-details.php?id=$id&amp;hit=1\">$dispname</a><br><font color=grey><small>&nbsp;Added:&nbsp; ".$time."</font></small> </td>");
            //vip

            break;
            case 'vip':
            $dispname1 ="";
              if ($row["vip"] == "y") {
                            $dispname1 = $dispname1 . "<img src='images/vip/vipsmall.png' / border=0  title=\"Vip\" >";
                            }
            //vip end
             if ($row["4ever"] == "y") {
                            $dispname1 = $dispname1 . "<img src='images/vip/4evervipsmall.png' / border=0  title=\"Vip 4Ever\" >";
                            }

            $last_access = $CURUSER["last_browse"];
            $time_now = gmtime();
            if ($last_access > $time_now || !is_numeric($last_access))
                $last_access = $time_now;
            if (sql_timestamp_to_unix_timestamp($row["added"]) >= $last_access)
                $dispname .= "<b><font color='#ff0000'> - (".T_("NEW")."!)</font></b>";

            if ($row["freeleech"] == 1)
                $dispname1 .= " <img src='images/vip/freeleechsmall.png' border='0' title=\"Freeleech\" />";
            print("<div id=left><center>$dispname1</center></div>");
        break;

                    case 'uploader':
            echo "<div id=left>";
            if (($row["anon"] == "yes" || $row["privacy"] == "strong") && $CURUSER["edit_torrents"] != "yes")
                echo "Anonymous";
            elseif ($row["username"])
                echo "<a href='account-details.php?id=$row[owner]'>$row[username]</a>";
            else
                echo "Unknown";
            echo "</div>";
        break;
        case 'comments':
            print("<div id=left><font size='1' face='verdana'><a href='comments.php?type=torrent&amp;id=$id'>" . number_format($row["comments"]) . "</a></font></div>\n");
        break;

        case 'size':
            print("<div id=left>".mksize($row["size"])."</div>\n");
        break;

        case 'seeders':
            print("<div id=left><font color='green'><b>".number_format($row["seeders"])."</b></font></div>\n");
        break;
        case 'leechers':
        $lots1 = $row['id'];

            print("<div id=left><font color='#ff0000'><b>" . number_format($row["leechers"]) . "</b>$lots1</font></div>\n");
        break;
                    case 'wait':
            if ($wait){
                $elapsed = floor((gmtime() - strtotime($row["added"])) / 3600);
                if ($elapsed < $wait && $row["external"] != "yes") {
                    $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
                    print("<div id=row><a href=\"faq.php#section46\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></div>\n");
                } else
                    print("<td class='ttable_col$x' align='center'>--</td>\n");
            }
        break;
        case 'rating':
            if (!$row["rating"])
                $rating = "<img src='images/rating/0.png' border=0>";
            else
                $rating = "<a title='$row[rating]/5'>".ratingpic($row["rating"])."</a>";
                //$rating = ratingpic($row["rating"]);
                 //$srating .= "$rpic (" . $row["rating"] . " out of 5) " . $row["numratings"] . " users have rated this torrent";
            print("<div id=left>$rating</div>");
        break;

        //km added book marks
        case 'Bookmark':
         if ($variant == "bookmarks") 
        echo "<div id=left><a href='bookmarktakedel.php?bookmarkid=$id' title='Delete'><img src='images/delchat.gif'                border='0' width='10px' alt='delete' title='delete' /></a></div>";
                    break;          
                    //end bookmarks


    }
    if ($x == 2)
        $x--;
    else
        $x++;
}





    //Wait Time Check
    if ($wait && !in_array("wait", $cols)) {
        $elapsed = floor((gmtime() - strtotime($row["added"])) / 3600);
        if ($elapsed < $wait && $row["external"] != "yes") {
            $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
            print("<div id=left><a href=\"faq.php\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></div>\n");
        } else
            print("<div id=left>--</div>\n");
        $colspan++;
        if ($x == 2)
            $x--;
        else
            $x++;
    }
    //$lots = $row['id'];

            print("</div></li>");

    //Expanding area
    if (count($expandrows)) {
        print("<tr><td class='ttable_col$x' colspan='$colspan'><div id=\"kt".$row['id']."\" style=\"margin-left: 2px; display: none;\">");
        print("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
        foreach ($expandrows as $expandrow) {
            switch ($expandrow) {
                case 'size':
                    print("<tr><td><b>".T_("SIZE")."</b>: ".mksize($row['size'])."</td></tr>");
                break;
                case 'speed':
                    if ($row["external"] != "yes" && $row["leechers"] >= 1){
                        $speedQ = SQL_Query_exec("SELECT (SUM(downloaded)) / (UNIX_TIMESTAMP('".get_date_time()."') - UNIX_TIMESTAMP(started)) AS totalspeed FROM peers WHERE seeder = 'no' AND torrent = '$id' ORDER BY started ASC");
                        $a = mysql_fetch_assoc($speedQ);
                        $totalspeed = mksize($a["totalspeed"]) . "/s";
                        print("<tr><td><b>".T_("SPEED").":</b> $totalspeed</td></tr>");
                    }
                break;
                case 'added':
                    print("<tr><td><b>".T_("ADDED").":</b> ".date("d-m-Y \\a\\t H:i:s", utc_to_tz_time($row['added']))."</td></tr>");
                break;
                case 'tracker':
                if ($row["external"] == "yes")
                    print("<tr><td><b>".T_("TRACKER").":</b> ".htmlspecialchars($row["announce"])."</td></tr>");
                break;
                case 'completed':
                    print("<tr><td><b>".T_("COMPLETED")."</b>: ".number_format($row['times_completed'])."</td></tr>");
                break;
            }
        }
            print("</table></div></td></tr>\n");
    }
    //End Expanding Area


}

5 个答案:

答案 0 :(得分:3)

function torrenttable1($res) {

     //[Table stuff]

    return $value;
}

电话会是:

$returnedVar = torrenttable1($res);

......有点难以理解这个问题。

答案 1 :(得分:2)

我不太明白你想做什么但是:

函数封装数据。即内部的内容不能也不应该被访问。它就像一个黑盒子,你把东西放进去,另一端,这个功能给你一些东西。

该功能总能通过return给您回复。但这只能做一次!一旦函数返回某些内容,它就会停止执行。

当然,您可以返回一个数组。这样您就可以返回多个值。但是又一次:当你返回一些函数停止并且调用代码恢复时......

答案 2 :(得分:0)

function func1($a) {
  return $a;
}
$a=5;
echo func1($a);

答案 3 :(得分:0)

return torrenttable1($res);

功能:

function torrenttable1($res)
{
.
return $xyz;
}

答案 4 :(得分:0)

为什么不将代码放在类中并为SQL返回的结果创建变量/数据数组?在这种情况下,您可以随时访问它们,并且可以在您的php文件中随处访问它们。

相关问题