简体   繁体   English

Codeigniter Datamapper ORM与数组和对象有关?

[英]Codeigniter Datamapper ORM issue with array and object?

I have a block code: 我有一个阻止代码:

    // 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;
        }
    }

My problem: $privileges contains all privileges in cms and $user_privileges contains privileges of a specific user. 我的问题: $ privileges包含cms中的所有特权,而$ user_privileges包含特定用户的特权。 I compare $privileges with $user_privileges : If user has the privilege which is marked as 1 else marked as 0 then I parse into view 我将$ privileges$ user_privileges进行比较:如果用户具有被标记为1的特权,否则被标记为0,则我将其解析为视图

$this->_data['privileges'] = $privileges;

In view, I must use $privileges['...'] (array) to show result but I want to use: $privileges->....(object) to do it. 看来,我必须使用$ privileges ['...'] (数组)来显示结果,但我想使用: $ privileges-> ....(对象)来执行此操作。

How can I do that? 我怎样才能做到这一点? Thank you very much. 非常感谢你。

If you omit the $privilege->all_to_array(...) line you can still assign new properties on the objects created. 如果省略$privilege->all_to_array(...)行,您仍然可以在创建的对象上分配新属性。

Just change the assignment syntax in your for loops like this: 只需在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;
    }
}

In the view now you can write it like this: 现在,在视图中,您可以这样编写:

<?php foreach ($privileges as $privilege): ?>
    <?php print $privilege->name ?> 
    The user <?php print $privilage->has_privilage ? 'have it' : 'dont have it' ?>.
<?php endforeach; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM