我有一个区块代码:
// Creat a object
$privilege = new Privilege();
// Get all privileges
$privilege->get_iterated();
$privileges = $privilege->all_to_array(array('id', 'name', 'description'));
// Get user privileges
$user_privileges = $privilege->get_user_privileges(array('id' => (int) $id), FALSE);
// If user has the privilege which is marked as 1,
// otherwise marked as 0
foreach ($privileges as $key => $item) {
foreach ($user_privileges as $value) {
$privileges[$key]['has_privilege'] = (in_array($value, $item) == TRUE) ? 1 : 0;
}
}
我的问题: $ privileges 包含cms中的所有权限, $ user_privileges 包含特定用户的权限。我将 $ privileges 与 $ user_privileges 进行比较:如果用户具有标记为1的权限,则标记为0,然后我将解析为视图
$this->_data['privileges'] = $privileges;
在视图中,我必须使用 $ privileges ['...'] (数组)来显示结果,但我想使用: $ privileges-> ....(对象)来做。
我该怎么做?非常感谢你。
答案 0 :(得分:0)
如果省略$privilege->all_to_array(...)
行,您仍可以在创建的对象上分配新属性。
只需更改for循环中的赋值语法,如下所示:
$privilege = new Privilege();
// IMPORTANT!
// Don't use get_iterated if you want to iterate on the results more than once!
$privilege->get();
$user_privileges = $privilege->get_user_privileges(array('id' => (int) $id), FALSE);
foreach ($privileges as $privilege) {
foreach ($user_privileges as $value) {
// the individual $privilage instances wont be cloned for the iteration
// so when we add has_privilage property they will "remember" it
// when you iterate on the same $privilages object once again in the vew
$privilege->has_privilege = (in_array($value, $item) == TRUE) ? 1 : 0;
}
}
现在在视图中你可以这样写:
<?php foreach ($privileges as $privilege): ?>
<?php print $privilege->name ?>
The user <?php print $privilage->has_privilage ? 'have it' : 'dont have it' ?>.
<?php endforeach; ?>