7

Could anyone shed any light as to why I can get this working.
I want to query an array to see if the USER->id that is currently logged in is assigned a specific role:

$contextroles = get_records_sql("SELECT userid FROM {$CFG->prefix}role_assignments WHERE contextid = 23 AND roleid = 3");

function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}

$alloweduser = object2array($contextroles);

if (in_array($USER->id, $alloweduser)) {
    echo'Your in<br />';
    echo $USER->id.'<br />';
    print_r($alloweduser);
}
else{
    echo'<br />You do not have permission to acces this database.<br />';
    echo $USER->id.'<br />';
    print_r($alloweduser);
    exit;
}

Im currently getting this output:

You do not have permission to acces this database.

5410

Array ( [7] => stdClass Object ( [userid] => 7 ) [9] => stdClass Object ( [userid] => 9 ) [27] => stdClass Object ( [userid] => 27 ) [98] => stdClass Object ( [userid] => 98 ) [203] => stdClass Object ( [userid] => 203 ) [252] => stdClass Object ( [userid] => 252 ) [5410] => stdClass Object ( [userid] => 5410 ) )

As you can see 5410 is in the array so should not get accessed denied. Thanks in advance for any help.

3
  • where is this variable/object $USER, $CFG come from? And what's wrong with object which you MUST convert it to array? Commented Sep 1, 2011 at 13:40
  • 11
    Your object2array() function is redundant. Casting an object to (array) has the same effect. Commented Sep 1, 2011 at 13:40
  • You're not saying, what the get_records_sql() does. Maybe you can just modify it so that it returns an array? What is $USER->id? And additionally I'm not sure if you can do a foreach on an object. Also, "5410" is not in the array but rather another stdObject which holds the userid "5410". That's a difference. Commented Sep 1, 2011 at 13:43

1 Answer 1

3

Because 5410 != stdClass Object ( [userid] => 5410 ) if you use in_array().

Since your array key looks like same with userid, you just use isset($alloweduser[$USER->id]) instead.

Sign up to request clarification or add additional context in comments.

2 Comments

also removed function: Your object2array() function is redundant. Casting an object to (array) has the same effect. – Rijk van Wel 2
@Codded Instead of isset(), use array_key_exists($USER->id,$alloweduser);

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.