php 将 stdClass 对象转换为数组
谁能解释一下为什么我可以让它工作。
我想查询一个数组以查看当前登录的 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;
}
我当前正在获取以下输出:
您没有访问此数据库的权限。
5410
Array ( [7] => stdClass 对象 ( [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)
正如你所看到的 5410因此数组不应被拒绝访问。 预先感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为如果您使用
in_array()
,则5410 != stdClass Object ( [userid] => 5410 )
。由于您的数组键看起来与
userid
相同,因此您只需使用isset($alloweduser[$USER->id])
即可。Because
5410 != stdClass Object ( [userid] => 5410 )
if you usein_array()
.Since your array key looks like same with
userid
, you just useisset($alloweduser[$USER->id])
instead.