2011-07-15 79 views
1

我有一個類方法,它返回多維的結果。我正在使用的方法是。如何合併多維數組到單維數組?

public function getUserRoles($userId) { 
    $sth = $this->dbh->prepare('SELECT role_id FROM user_roles WHERE user_id = :userId'); 
    $sth->bindParam(':userId', $userId); 
    $sth->execute(); 
    $roles = array(); 
    while($row = $sth->fetch(PDO::FETCH_ASSOC)) { 
     $roles[] = array($row['role_id']); 
    } 
    return $roles; 
} 

,當我調用該方法

print_r($acl->getUserRoles(1)); 

結果返回集我得到的是。

Array ([0] => Array ([0] => 1) [1] => Array ([0] => 2) [2] => Array ([0] => 3) [3] => Array ([0] => 4) [4] => Array ([0] => 5)) 

但是,我不希望值在多維數組中返回,而是我想上面返回的結果是。

Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5) 

是否有任何PHP的本地功能來照顧這個?

謝謝

回答

3

如果與PDO::FETCH_COLUMN選項中使用的fetchAll功能服務於這一確切目的:

$roles = $sth->fetchAll(PDO::FETCH_COLUMN); 
return $roles; 
+0

哦耶,聽起來很棒,很簡單謝謝喬恩:) –

+0

謝謝!我正要問這個問題。 – octern

3

更改這行代碼

$roles[] = array($row['role_id']); 

$roles[] = $row['role_id']; 

in getUserRoles方法