php - PDO 数组和 array_unique

标签 php pdo

我正在尝试使用 PDO 从我的数据库中返回一个类(class) ID 列表。我可以访问数据,但是,我只想返回一组唯一 ID,即

这个

1,2,2,3,4,4

成为

1,2,3,4

我正在使用下面的代码

$sth = $dbh->prepare('SELECT courseId from training');  
    $sth->execute();  
        $row = $sth->fetchAll();
        $result = array_unique($row);
        print_r($result); 

但是,它只返回 1 个 id:

Array ( [0] => Array ( [courseId] => 8 [0] => 8 ) )

如果我 print_r $row 我可以看到我所有的 courseId

我做错了什么?

最佳答案

What am I doing wrong?

您没有阅读友好的 manualarray_unique 上,您可以在其中看到:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

由于 $result 包含数组,并且每个数组的字符串表示形式相同(“Array”IIRC),因此所有元素比较“相等”,只剩下第一个。

如何解决问题:几种方法。

一种方法是使用 SELECT DISTINCT 让数据库为您完成。

另一种方法是从一个数组数组变成一个只有 id 的数组,然后 array_unique 就可以正常工作了。这可以简单地使用 foreach 循环完成,或者(可能更好)使用 array_map,例如:

$ids = array_map(function($el) { return $el['courseId']; }, $row);
$unique = array_unique($ids);

关于php - PDO 数组和 array_unique,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9728051/

相关文章:

php - 如何链接到 html 文档中的 gzip javascript?

php - $this 变量在 PHP 中的行为

php - MySQL 函数声明。不适用于 PHP。从 phpmyadmin 运行没问题。不创建函数

php - 即使我知道参数的类型,我还需要准备语句吗?

php - 尝试使用 beginTransaction() 和 commit() 但当我将命令放入时失败

php - 从数据库字段值构建 PHP 数组字符串

php - Android 中的 FIrebase 401 未授权错误 FCM

PHP PDO : Why cause this error in sql statement?

php - SQLSTATE[HY000] [2002] 权限被拒绝 Laravel PDO 驱动程序(通过 artisan migrate 工作的凭据)

php - 动态 jquery 中未捕获的语法错误