array_unique 在 PHP 中不起作用?
我的 MySql 数据库中有一个表:
pageid | text
-----------+----------
1 | test
-----------+----------
2 | example
-----------+----------
3 | another
-----------+----------
1 | example1
和这个 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>";
}
}
但它返回:
1
2
3
1
我想让 pageid
唯一。所以我想回显一次数字1
。就像这样:
1
2
3
那么我做错了什么?我怎样才能实现我想要的目标?
预先感谢...
[我知道这段代码没有多大意义,但这只是这个问题的演示,我有一个更复杂的代码:)]
I have got a table in my MySql database:
pageid | text
-----------+----------
1 | test
-----------+----------
2 | example
-----------+----------
3 | another
-----------+----------
1 | example1
and this PHP code:
$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. So I would like to echo out the number 1
, once. 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 :) ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,在这种情况下真正的答案是首先选择不同的记录:
但是至于为什么你的代码不起作用......
你将
$id1
声明为数组,但不附加到它。相反,您每次只是创建一个 1 元素数组。相反,附加所有结果,然后调用 array_unique()Of course, the real answer in this situation is to select distinct records to begin with:
But as to why your code doesn't work...
You are declaring
$id1
as an array, but not appending to it. Instead you're just creating a 1 element array each time. Instead, append all results then callarray_unique()
您可以在
SELECT
中执行以下操作:SELECT DISTINCT pageid FROM test
或使用GROUP BY
,如下所示:You could do it in your
SELECT
by doing something likeSELECT DISTINCT pageid FROM test
or by usingGROUP BY
like this:您可以在 sql 查询中使用 Distinct 关键字。这将返回 Page 的唯一值
You can use Distinct keyword in your sql query.That will return you the unique vaues of Page