1

I have a class method which returns the result in multidimension. the method i am using is.

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;
}

and when i call the method

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

the returned set of result i get is.

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

However i do not want the values to be returned in multidimensional array instead i would like the above returned result to be.

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

Is there any PHP's native function to take care of this?

Thank you

2 Answers 2

3

The fetchAll function serves this exact purpose if used with the PDO::FETCH_COLUMN option:

$roles = $sth->fetchAll(PDO::FETCH_COLUMN);
return $roles;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was just about to ask this very question.
3

Change this line of code

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

to

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

in getUserRoles method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.