0

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

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

In view, I must use $privileges['...'](array) to show result but I want to use: $privileges->....(object) to do it.

How can I do that? Thank you very much.

tereško
  • 58,060
  • 25
  • 98
  • 150
Joshua Hansen
  • 405
  • 1
  • 8
  • 21
  • Can't you move the filtering to sql land, only selecting the `Privilage` instances that are available for the user? If you, for example can return the `Privilage` ID's from `get_user_privilages` for the user then it's only a `where_in()`. Also, why the continious-integration tag? – complex857 Apr 18 '13 at 12:48
  • so in this case, I can't work with object and still use array as above code. – Joshua Hansen Apr 18 '13 at 13:18

1 Answers1

0

If you omit the $privilege->all_to_array(...) line you can still assign new properties on the objects created.

Just change the assignment syntax in your for loops like this:

$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; ?>
complex857
  • 20,425
  • 6
  • 51
  • 54