开发者

PHP foreach loop problem

I have the following code:

//generate 10 top tags
$tagSQL = mysql_fetch_array(mysql_query("SELECT * FROM tags"));
$topArray = array();
foreach($tagSQL as $poland)
{
    if($poland["tagID"] == 1)
    {
        $topArray[0] ++;
    }
    开发者_如何学Pythonif($poland["tagID"] == 2)
    {
        $topArray[1] ++;
    }
    if($poland["tagID"] == 3)
    {
        $topArray[2] ++;
    }
    if($poland["tagID"] == 4)
    {
        $topArray[3] ++;
    }
}
function printTopTags()
{
    $n = 0;
    foreach($topArray as $buddha)
    {
        $n = $n + 1;
        if(sizeOf($topArray) > $n)
        {
            $hersheyBar = " ";
        }
        else
        {
            $hersheyBar = "";
        }
        $finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'"));
        foreach($finalFinalEndArray as $waterBottle)
        {
            echo $waterBottle . $hersheyBar;
        }
    }   
}

I get the error Warning: Invalid argument supplied for foreach() on line 93

Line 93 is foreach($topArray as $buddha).

Any help?


http://ru.php.net/manual/en/language.variables.scope.php

Also

if($poland["tagID"] == 1)
{
    $topArray[0] ++;
}
if($poland["tagID"] == 2)
{
    $topArray[1] ++;
}
if($poland["tagID"] == 3)
{
    $topArray[2] ++;
}
if($poland["tagID"] == 4)
{
    $topArray[3] ++;
}

===

if ($poland["tagID"] >= 1 && $poland["tagID"] <= 4)
    $topArray[$poland["tagID"] - 1]++;


$tagSQL = mysql_fetch_array(mysql_query("SELECT * FROM tags"));

This is very bad practice. If the query fails for any reason whatsoever, mysql_query returns boolean FALSE, which you then blindly pass to mysql_fetch_array, which will then fail in turn because it's expect a mysql result handle, not a boolean, and return a boolean itself.

You then use all this failed data in a foreach loop, and wonder why you're not getting anything but errors?


Looks like $topArray just not defined in printTopTags() function. You can pass it as a parameter:

function printTopTags($topArray) {
...
}


$topArray is a global variable.

To use it inside a function you either have to pass it as a parameter or use the global keyword to import it:

function printTopTags()
{
    global $topArray;  // <---- Here!
    $n = 0;
    foreach($topArray as $buddha)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜