Hi guys,

I have one simple logical question that I seem not to figure it out, sadly...

We have a list of objects and I loop trough them, list of products.
We need to create anchor maps for each category, so I did a comparison with temp variables to check the previous and current element value.

How can I display only the first occurence of a series of values for each category ?

Desired result:

Category 1
- product 1
- product 2
- product 3
Category 2
- product 1
- product 2
- product 3

    $previous = '';
    if(!empty($promotii)) {
        foreach($promotii as $promotie) {
            $previous = $promotie->Marca;
        }
        $previous = $promotie->Marca;
     }

Recommended Answers

All 2 Replies

Something like this:

$previous = '';
foreach($promotii as $promotie) 
{
    if ($previous != $promotie->Marca)
    {
        if (!empty($previous))
        {
            echo '</ul>';
        }

        $previous != $promotie->Marca;

        echo $promotie->Marca . '<ul>';
    }

    echo "<li>$promotie->Product</li>";
}

if (!empty($previous))
{
    echo '</ul>';
}

Thanks pritaeas for the heads up, it was a great start :)
This is my final implementation and it works great.

        echo '<table width="600" cellpadding="0" cellspacing="0" border="0" class="table table-condensed">';    
        echo '<tbody>';        
        $previous = '';
        foreach($promotii as $promotie) {            
            if ($previous != $promotie->Marca) {
                if (!empty($previous)) {
                } else {
                    $previous = $promotie->Marca;
                }

                echo '<tr>';
                    echo '<td>';
                        echo $promotie->Marca;
                    echo '</td>';
                echo '</tr>';                  
            }

            echo '<tr>'; // start product stuff
            echo '</tr>'; // end of product stuff

            $previous = $promotie->Marca;
        }
        echo '</tbody>';
        echo '</table>';      
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.