试图从数组acc中删除重复的行。到列内容

时间:2014-09-16 21:20:23

标签: php mysql sql arrays duplicates

使用PHP并从DB进行SELECT查询我得到了一个我不喜欢的输出。

我是这样开始的:

$details = Db::getInstance()->executeS($sql);

之后我得到了
echo json_encode($details);

出于调试目的:

[{"email":"test@on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]   
[{"email":"test@on.gr","lastname":"OTHER","firstname":"DIFFERENT","id_lang":"1","id_order":"2"}]
[{"email":"test@on.gr","lastname":"THIRD","firstname":"DIFFERENT","id_lang":"1","id_order":"3"}]
[{"email":"new@on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]

我想要的是转换数组$details以检查每条"线"如果电子邮件列在整个输出上具有唯一值。如果是,则删除包含重复条目的行,并仅保留包含重复条目的第一行。

期望的输出

[{"email":"test@on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]
[{"email":"new@on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]

(正如你看到ID为2和3的行被删除,因为它们与第一个有相同的电子邮件)

任何形式的帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

编辑:只是想在这里添加我的代码不在PHP中。你必须改变它。

在select语句中执行ORDER BY email命令。 伪代码:

循环结果:

String email1 = "";
String email2 = "";
for (i=0;i<(Detailssize); i++){

  email2 = details[email][i]; //Do whatever you need to do to access the value of the email key here.
  if(email2 != email1){
      KEEP IT
  }
  else{
   THROW AWAY
  }
  email1 = email2;

}

显然这不是PHP。自从我编写php以来已经有一段时间了。尽管如此,逻辑上这应该仍然有效。我确定有一种方法可以将SELECT语句更改为仅从每个值返回一个,但我对SQL不够好。这不是一个好的解决方案,但希望它有所帮助。

答案 1 :(得分:0)

保留您之前见过的电子邮件列表;每当您遇到之前见过的电子邮件时,请跳过该行。

像这样:

$newSet = array();
$seenBefore = array();
foreach( $details as $row ) {
  if( isset( $seenBefore[ $row['email'] ) ) { 
    continue; // jump to the next row
  }
  // this email address must be new; add it to things we've seen before then add this row to the newSet
  $seenBefore[$row['email']] = true;
  $newSet[] = $row;
}

然后以你想要的任何方式输出$ newSet。