Search code examples
phpmysqlarrays

Avoid displaying duplicate results in PHP from database


I have been trying to manage duplicate data which is shown to users.

I thought I can add the varibales to arrays and use the function array_unique

I want to be able to manage the rows which contain a duplicate date and split them into different sections for example

if(duplicate.exists == true)
{
 //do something to the duplicate row
}
else
{
//do something to the row which isnt a duplicate
}

I cant figure out why array_unique is not working.

Help would be appreciated, Thanks.

$result = mysqli_query($con, "SELECT *
        FROM quotes order by DATE asc ");

        $index1 = array();
        $fact1 = array(); 
        $newDate1 = array();

        while ($row = mysqli_fetch_array($result)) {

            $index = $row['id'];
            $dbdate = $row['date'];
            $fact = $row['quote'];

            $newDate = date("d-m-Y", strtotime($dbdate));

            $index1[] = $fact;
            $fact1[] = $fact;
            $newDate1[] = $newDate;

        }

Then have a function which loops through each array and finds out if a certain date has already exists.

for($i=0; $i<count($index1); $i++) {

 echo(array_unique($newDate1));

}

 else
{

}

Thats an example of the data that will be in the DB. It's the id, fact, date example 1, fact, 2015-01-22

1 Steve Jobs unveiled the first Apple #Mac computer and changed technology forever (1984) - 2015-01-24
2 In 2011, the Urban Technology Innovation Center was launched in New York City - 2015-01-25
3 #Bebo was launched a whole decade ago today (2005), who feels old? - 2015-01-26
4 Sun Microsystems was acquired by Oracle Corporation for $7.4 bn (2010) - 2015-01-27

Solution

  • Considering you are sorting your query on date and that makes something a duplicate, all you need to do is track the last date.

    $lastdate = '';
    while ($row = mysqli_fetch_array($result)) {
        $dbdate = $row['date'];
    
        if ($lastdate==$dbdate) {
          //duplicate
        } else {
          //first or unique
        }
    
        $lastdate = $dbdate;
    
    
    }