简体   繁体   English

array_unique在PHP中不起作用?

[英]array_unique not working in PHP?

I have got a table in my MySql database: 我的MySql数据库中有一个表:

  pageid   | text
-----------+----------
    1      | test
-----------+----------
    2      | example
-----------+----------
    3      | another
-----------+----------
    1      | example1

and this PHP code: 这个PHP代码:

$query = "SELECT pageid FROM test";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
  {
  $id = $row['pageid'];
  $id1 = array($id);
  $id2 = array_unique($id1);
  foreach ($id2 as $value)
    {
    echo $value . "<br>";
    }
  }

But it returns: 但它返回:

1
2
3
1

I would like to make the pageid s unique. 我想使pageid独一无二。 So I would like to echo out the number 1 , once. 所以我想回答1 ,一次。 Like this: 像这样:

1
2
3

So what am I doing wrong? 那么我做错了什么? How could I achieve what I want? 我怎么能实现我想要的?

Thanks in advance... 提前致谢...

[I know that this code doesn't make much sense, but this is just a demo for this question and I have a much more complicated code :) ] [我知道这段代码没有多大意义,但这只是这个问题的一个演示,我有一个更复杂的代码:)]

Of course, the real answer in this situation is to select distinct records to begin with: 当然,在这种情况下,真正的答案是选择不同的记录开头:

$query = "SELECT DISTINCT pageid FROM test";

But as to why your code doesn't work... 但至于为什么你的代码不起作用......

You are declaring $id1 as an array, but not appending to it. 您将$id1声明为数组,但不附加到它。 Instead you're just creating a 1 element array each time. 相反,你每次只是创建一个1元素数组。 Instead, append all results then call array_unique() 相反,追加所有结果然后调用array_unique()

$query = "SELECT pageid FROM test";
$result = mysql_query($query);

// Declare array first
$id1 = array();
while($row = mysql_fetch_array($result))
  {
  $id = $row['pageid'];
  // Append to the array...
  $id1[] = $id;
  }

// Call array_unique() outside the loop:
$id2 = array_unique($id1);
foreach ($id2 as $value)
{
  echo $value . "<br>";
}

您可以通过执行SELECT DISTINCT pageid FROM test或使用GROUP BY类的操作在SELECT执行此操作:

SELECT pageid FROM test WHERE 1 GROUP BY pageid 

您可以在sql查询中使用Distinct关键字。这将返回页面的唯一值

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

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