Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

How to merge multidimensional array to single dimension array?

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

Upvotes: 1

Views: 648

Answers (2)

Shakti Singh
Shakti Singh

Reputation: 86336

Change this line of code

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

to

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

in getUserRoles method

Upvotes: 3

Jon
Jon

Reputation: 437336

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

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

Upvotes: 3

Related Questions