简体   繁体   中英

Print same rows as once in php while loop

I have three colums which has same values for two of the rows. I want to print only one of a same row out of the two same rows using a php while loop statement. This is how the data is

ID   values
1     MINI
1     MINI
2     MINI

I want to print all of these but only once with same rows based on the ID

 ID    Values
  1     MINI
  2     MINI

I can actually use DISTINCT OR GROUP BY in mysql query to find the expected answer above but I really need to use a php while statement.

This is what I have been trying my hands on

$query="SELECT * from table";
$sR=$db->query($query);

$array=array();

while($sRow=mysqli_fetch_assoc($sR)){
   $ID=$searchRow['ID'];
   $values=$searchRow['Values'];

   $array[$ID][]=$ID;   
   $array2[$ID][]=$values;  
}

foreach($array as $ID => $item){
    $value=$array[$ID];
    foreach($item as $newItem){
        if($newItem===$newItem){
           echo '---'.$newItem;
           break;
        }
    }
}

This is what I am trying hands on but it doesn't seem to work as expected, I would need help on it. Thanks soo much.

When I do things like this I use a "Previous ID"-variable, in this case $PRID, to check if the ID is a duplicate. The SQL query has to be ordered by ID to make this work.

$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);

$array=array();

$PRID=0;
while($sRow=mysqli_fetch_assoc($sR)){
   $ID=$searchRow['ID'];
   $values=$searchRow['Values'];
   if($ID>$PRID){
      $array[$ID][]=$ID;   
      $array2[$ID][]=$values;  
   }
   $PRID=$ID;
}

foreach($array as $ID => $item){
    $value=$array[$ID];
    foreach($item as $newItem){
        if($newItem===$newItem){
           echo '---'.$newItem;
           break;
        }
    }
}

just try option 1 or option 2

$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);

$array = array();

// first option, expected output
// array(
//   0 => 'value',
//   1 => 'value'
// )
foreach($sR as $value) {
  $array[$value['ID']] = $value['Values'];
}

var_dump($array);

$array2 = array();
// second option
foreach($sR as $value) {
  $array2[$value['ID']] = array(
    'ID' => $value['ID'],
    'Value' => $value['Value']
  );
}

var_dump($array2);
// expected output
// array(
//  0 => array(
//    'ID' => 0,
//    'Value' => 'value'
//  ),
//  1 => array(
//    'ID' => 1,
//    'Value' => 'value'
//  )
// )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM