0

我有一个块代码:

    // 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['...'] (array) 来显示结果,但我想使用:$privileges->....(object)来做到这一点。

我怎样才能做到这一点?非常感谢。

4

1 回答 1

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; ?>
于 2013-04-18T20:13:45.640 回答