views:

140

answers:

3

Okay, so I followed the advice on this question: http://stackoverflow.com/questions/1214176/stumped-in-the-middle-of-a-php-loop

But now, I'm having even more problems than before. Here's what I have so far:

$sql = "SELECT section_name, category_name, result_level, url, winner FROM 2009_RKR_bestof INNER JOIN categories ON 2009_RKR_bestof.category = categories.category_id INNER JOIN sections ON 2009_RKR_bestof.section = sections.section_id ORDER BY section_name,category_name ASC";
$query = mysql_query($sql);

$current_section = "";
while ($stuff = mysql_fetch_array($query)) {
    if ($current_section == "") {
        $current_section = $stuff["section_name"];
        echo "<h3>$current_section</h3>";
        echo "<h4>$stuff[category_name]</h4>";
    }
    if ($current_section == $stuff["section_name"]) {
            //what the heck do i do here?

    } elseif ($current_section != $stuff["section_name"]) {
        $current_section = $stuff["section_name"];
        echo "<h3>$current_section</h3>";
    }
}

And my output is here: http://www.theroanoker.com/bestof/index1.php
By my old code, I had gotten this far: http://www.theroanoker.com/bestof/index2.php

I'm beating my head against the wall. Can someone guide me a bit more?

+1  A: 

Even though it is slower, I think it is usually easier to understand if you pass through the loop once and sort things out. So, don't echo anything on the first pass, but create a couple of arrays, like $sections = array(); and $categories = array(); Then, when you look through, do something like $categories[$stuff["category_name"]] = $stuff, and the same for the section.

Then make a second loop through the categories and sections array and print them out

Sean Clark Hess
+1  A: 

Caveat: with neither a var_dump of $stuff nor a knowledge of the structure of your tables, it's hard to intuit the nature of the results you'll get back. That said, I think your joins will produce a sequence of rows with data from some tables repeated - your 'section_name' column, for one.

If so, then you've got the right general idea with your loop, you just need to add some code to output a list. This could take the form of a nested loop that runs until $stuff["section_name"] changes. Your loop then becomes:

$stuff = mysql_fetch_array($query);
while ($stuff) {
    echo "<h3>{$stuff['section_name']}</h3>";
    echo "<h4>{$stuff['category_name']}</h4>";

    $current_section = $stuff['section_name'];
    echo '<ul>';  //start list
    while ($current_section == $stuff['section_name'])  {
        echo '<li>'. /* Your data here */ .'</li>';

        $stuff = mysql_fetch_array($query);
    }
    echo '</ul>';
}

Warning The above fails if your results aren't ordered such that all results containing a given "section_name" are contiguous in the results array.

Ryan Ballantyne
A: