0

I have pass trough array to get all ROLE field results from db.

Not I need to search them to find just ROLE_ADMIN roles and count them.

"users": [
    [
        "ROLE_SUPER_ADMIN"
    ],
    [
        "ROLE_STRATEGIST",
        "ROLE_ADMIN"
    ],
    [
        "ROLE_EDITOR"
    ],
    [
        "ROLE_STRATEGIST",
        "ROLE_ADMIN"
    ],
]

And this is my code:

$users = $this->entityManager->getRepository(User::class)->findAll();

    $countUsers = [];
    foreach ($users as $user) {
        $countUsers[] = $user->getRoles();
    }

    return $countUsers;

Is there a way to go trough array and count all ROLE_ADMIN results?

2
  • Something like $role_admin_counter += in_array('ROLE_ADMIN', $user->getRoles()) ? 1 : 0; …? Commented Sep 29, 2020 at 9:26
  • Yap! This was great, thanks! @04FS Commented Sep 29, 2020 at 9:36

1 Answer 1

1

If the input is available as an array as shown, it can also be implemented with the array_reduce function.

$users = [
    ["ROLE_SUPER_ADMIN"],
    ["ROLE_STRATEGIST","ROLE_ADMIN"],
    ["ROLE_EDITOR"],
    ["ROLE_STRATEGIST","ROLE_ADMIN"],
];

$role = 'ROLE_ADMIN';
$count = array_reduce(
  $users,
  function($carry,$item) use($role){return $carry + (int)in_array($role,$item);},
  0
);

var_dump($count); //int(2)
Sign up to request clarification or add additional context in comments.

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.