简体   繁体   English

在php循环中打印相同的行一次

[英]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. 我想使用php while循环语句从两个相同的行中只打印同一行中的一行。 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的相同行

 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. 我实际上可以在mysql查询中使用DISTINCT OR GROUP BY来查找上面的预期答案,但我真的需要使用php while语句。

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. 非常感谢soo。

When I do things like this I use a "Previous ID"-variable, in this case $PRID, to check if the ID is a duplicate. 当我做这样的事情时,我使用“Previous ID” - 变量,在这种情况下是$ PRID,来检查ID是否重复。 The SQL query has to be ordered by ID to make this work. 必须按ID对SQL查询进行排序才能使其正常工作。

$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 只需尝试选项1或选项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'
//  )
// )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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