Ricardo Miller
Ricardo Miller

Reputation: 1

Loopiing over array

array(4) { 

    [0]=> array(1) 
        { ["perm_desc"]=> string(10) "Can Delete" } 
    [1]=> array(1) 
        { ["perm_desc"]=> string(8) "Can Edit" } 
    [2]=> array(1) 
        { ["perm_desc"]=> string(10) "Can Create" } 
    [3]=> array(1) 
        { ["perm_desc"]=> string(16) "Can Manage Roles" } 
}

I am struggling to find the right way to loop over these arrays. so basically i have pulling all permissions from the database and i want it in 1 single array so i can manipulate late when needed. but the database is spittiing this data out in multiply arrays.

$results = static::customQuery($sql, ["role_id" => $role_id]);
if ($results) {
        foreach ($results as $r) {
            var_dump($r);
            die();
}

I get this back just 1 result from the original array which contains 4 array

array(1) { ["perm_desc"]=> string(10) "Can Delete" }

but really i want something like this

['Can Edit', 'Can Manage', 'Can Create', 'Can Manage Roles']

and idea would be really helpful

Upvotes: 0

Views: 32

Answers (2)

Ricardo Miller
Ricardo Miller

Reputation: 1

I manage to fix the issue

static function results()
{
    if (static::exec()) {
        $results = static::$stmt->fetchAll();
        return $results;
   }
}

this is a part of my code base I change it to

static function results()
{
    if (static::exec()) {
        $results = static::$stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
   }
}

by adding PDO::FETCH_ASSOC

did my looping in my Roles class

$results = static::customQuery($sql, ["role_id" => $role_id]);
    if ($results) {
        foreach ($results as $result) {
            $role->permissions[$result["perm_desc"]] = true;
        }

    }
    var_dump($role);
    die();

and now i am getting back the desired results

    object(Core\Layers\Roles)#14 (1) { 
["permissions":protected]=> 
array(8) { 
["Can Delete"]=> bool(true) 
["Can Edit"]=> bool(true) 
["Can Create"]=> bool(true) 
["Can Manage Roles"]=> bool(true) 
["Can Backup"]=> bool(true) 
["Can Download"]=> bool(true) 
["Create Menu"]=> bool(true) 
["test"]=> bool(true) 
} 
}

Upvotes: 0

Anonymous
Anonymous

Reputation: 12017

array_column was made for this:

$results = array_column($results, 'perm_desc');

Upvotes: 1

Related Questions