php将stdClass对象转换为数组

时间:2022-10-23 07:54:33

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:

任何人都可以解释为什么我可以让这个工作。我想查询一个数组,看看当前登录的USER-> id是否被分配了一个特定的角色:

$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

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 ) )

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

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

正如您所看到的,5410位于数组中,因此不应被拒绝访问。在此先感谢您的帮助。

1 个解决方案

#1


3  

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

因为5410!= stdClass对象([userid] => 5410),如果你使用in_array()。

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

由于您的数组键与userid看起来相同,因此您只需使用isset($ alloweduser [$ USER-> id])。

#1


3  

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

因为5410!= stdClass对象([userid] => 5410),如果你使用in_array()。

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

由于您的数组键与userid看起来相同,因此您只需使用isset($ alloweduser [$ USER-> id])。