Jump to content

Testing for and hiding duplicate rows in array


garfee
Go to solution Solved by garfee,

Recommended Posts

Hi there.

 

I am trying to hide duplicate rows that are generated in my while loop.

 

My php is this:

<?php

// Start looping rows in mysql database.
$prev_category_name = false;
while($rows=mysql_fetch_array($result))
{
    $category_name = ($rows['category_id']);
    $items = ($rows['items']);
    $price = ($rows['price']);
        
        if ($category_name == $prev_category_name)
            {
                $category_name = '';
                    }
?>


<table>
<th><?php echo "$category_name"?></th>
<tr>
<td><?php echo "$items"?></td>
<td><?php echo "$price"?></td>
</tr>
</table>
<?php
$prev_category_name = $category_name;
}


?>

However. It only hides the duplicate if I have 2 or more items listed. For example, it would ouput this:

 

SHOES

Brown             £25.00

Red                £25.00

SHOES

Yellow             £25.00

 

When what I need it to output is this:

 

SHOES

Brown             £25.00

Red                £25.00

Yellow             £25.00

 

I am guessing it is doing this because the php is only testing the previous row for a duplicate, but I am not sure how to test all rows for a duplicate. Or even if this is the right thing to be doing.

 

Could anyone offer some advice and point me in the right direction.

 

Many thanks in advance.

 

ps. I am aware that DISTINCT in my SQL statement may solve the issue, but I want to be able to solve it using php.

Edited by garfee
Link to comment
Share on other sites

You are creating a separate TABLE for each product. You need to move the TABLE tag to a place BEFORE the loop, and the closing TABLE tag to a place AFTER the loop.

 

The TH element needs to be INSIDE a table row

 

Your main problem is that you are setting $category to am empty string to stop it from printing. Then you assign $category to $prev_category_name to test the next iteration. Well, now the previous category is NOT equal to the next one. Do not change the category, as Barand showed, just output the heading inside the IF test if the current category does not match the previous one.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.