Distinct values from while loop

I have a database with a field called part_name. with the values:

Front Control Arm, Rear Control Arm

I need to echo out only Control Arm, once only. As of now what i'm getting on the while loop results is

Control Arm, Control Arm.

Need to echo out distinct values from while loop results. I can't do it on the SQL query SELECT DISTINCT because i'm preg replacing the value from the row that i'm queering on the database.

while ($rowsparts = mysql_fetch_array($displayparts))    {
     $part=''.$rowsparts['part_name'].''; 
     $part = preg_replace('/bFrontb/u', '', $part);
     $part = preg_replace('/bRearb/u', '', $part);  
     echo '<li>'.$part.'</li>';
}

I need to echo out the $part variable distinct values, only once per part name.

Control Arm only.


This might work if you want to only display the part name once:

$lastpart = '';
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name']; 
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if($lastpart != $part) {
        $lastpart = $part;
        echo "<li>".$part."</li>n";
    } else {
        echo "<li>Part name duplicate: $part, lastpart: $lastpart</li>n";
    }
}

I added the else for debugging. It will show the two vars that are used to detect duplicates. You would remove it after testing.

This might work if you want to only display the part name once when the part names are not in order. It builds a list of part names, and checks each part names against the list, showing only the ones not found in the list.

$part_list = array();
while ($rowsparts = mysql_fetch_array($displayparts)) {
    $part = $rowsparts['part_name']; 
    $part = trim(str_replace('Rear','',str_replace('Front','',$part)));
    if(!isset($part_list[$part])) {
        $part_list[$part] = 1;
        echo "<li>".$part."</li>n";
    }
}
链接地址: http://www.djcxy.com/p/59738.html

上一篇: foreach循环不会从$返回值

下一篇: while循环的不同值