多个foreach - 第一个结果不显示

时间:2014-07-07 10:43:27

标签: php foreach

我正在玩下面的代码,我正在创建我个人的“音乐数据库”。在我的mysql中,我有以下表格:

  • 音乐类别
  • 音乐艺术家
  • 音乐曲目

下面的代码工作正常,除了它不显示数据库的第一个轨道,它跳过它,但它显示所有其余的就好了。如果我采用以下示例,显示的数据如下:

    Category: 70's
    artist2       trackname2

    Category: 90's
    artist3       trackname3

所以,跳过了第一首曲目。我一直在玩代码,但我无法让它工作。它应该显示如下:

    Category: 70's
    artist1       trackname1
    artist2       trackname2

    Category: 90's
    artist3       trackname3

数据库中的样子示例:

    music_categories:

    musicID     name
    1           70s
    2           80s
    3           90s


    music_artists:

    artistID    name
    1           artist1
    2           artist2
    3           artist3


    music_tracks:

    id  musicID     artistID    track

    1   1           1           trackname1
    2   1           2           trackname2
    3   3           1           trackname3

每首音乐曲目都有一位艺术家和一个类别。我在classes.php文件中使用下面的代码:

public function grabResults($table)
{
    $result = 'SELECT * FROM '.$table;

    $query = $this->mysqli->query($result);

    if($query)
    {
        while($row = $query->fetch_assoc())
        {
            $rows[] = $row;
        }
            return $rows;
    }
    else {
        return false;
    }
}

这就是代码本身:

    $categories     = $data->grabResults(music_categories);
    $artists    = $data->grabResults(music_artists);
    $tracks     = $data->grabResults(music_tracks);

    $catName    = '';
    $counter    = 0;

foreach ($categories as $category)
{
    foreach ($tracks as $track)
    {
        if($category['name'] != $catName)
        {
            $countID    = $category['id'];
            $total      = $data->mysqli->query("SELECT `musicID` FROM `music_tracks` WHERE `musicID` = '$countID' "); 
            $totalCount     = $total->num_rows;

                if($totalCount > 0)
                {
                    echo $category['name'];
                }

            $catName    = $category['name'];
            $counter    = 0;
        }
            if($counter > 0)
            {
                if($category['id'] == $track['mid'])
                {
                    foreach ($artists as $artist)
                    {
                        if($track['artistID'] == $artist['id'])
                        {
                            echo $artist['name'];
                        }
                    }
                        echo $track['track'];
                        echo "<br>";
                }
            }
    $counter++;

    }
}

0 个答案:

没有答案