1

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.

2 Answers 2

0

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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'
//  )
// )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.