动态访问多维stdClass数组 - Codeigniter

时间:2014-08-22 03:34:17

标签: php arrays codeigniter multidimensional-array foreach

我想知道如何使用嵌套的foreach循环访问以下数组?

   Array ( [0] => 
   Array ( [0] => stdClass Object ( [roleID] => 3 [permID] => 2 ) 
           [1] => stdClass Object ( [roleID] => 3 [permID] => 3 ) 
           [2] => stdClass Object ( [roleID] => 2 [permID] => 4 )
           [3] => stdClass Object ( [roleID] => 2 [permID] => 5 ) ) 

这是我的代码:

    foreach($allPermissions as $allPermission) :

     foreach($rolePermissions as $rolePermission) :  

         if($allPermission->ID==$rolePermission[0]->permID) {  ?>

          <div class="perms">
            <input type="checkbox" name="permissions[]" id="<?php echo $allPermission->ID; ?>"  value="<?php print $allPermission->ID; ?>"  checked><?php print $allPermission->permName; ?></option></div>
         <?php } 
        endforeach;
     endforeach;  ?>

这样我就可以得到与索引0相关的结果但是如果数组索引超过0则无法得到结果。

答案

我想出了以下代码:

             foreach($rolePermissions as $key=>$val) :  
                   foreach($val as $subkey=>$subval)
                        {

                  if($allPermission->ID==$subval->permID) {
            ?>
          <div class="perms">
           <input type="checkbox" name="permissions[]" id="<?php echo $allPermission->ID; ?>"  value="<?php print $allPermission->ID; ?>"  checked><?php print $allPermission->permName; ?></option></div>
            <?php }  }

2 个答案:

答案 0 :(得分:0)

如果我理解正确的话应该是这样的

// Iterating all permissions

foreach($allPermissions as $allPermission){

// Iterating the roles of a specific permission

    foreach($allPremisson as $rolePermission) {

    }
}

答案 1 :(得分:0)

试试这个:

foreach($allPermissions as $allPermission) :

     foreach($rolePermissions as $key=>$rolePermission) :  

         if($allPermission->ID==$rolePermission[$key]->permID) {  ?>

          <div class="perms">
            <input type="checkbox" name="permissions[]" id="<?php echo $allPermission->ID; ?>"  value="<?php print $allPermission->ID; ?>"  checked><?php print $allPermission->permName; ?></option></div>
         <?php } 
        endforeach;
     endforeach;  ?>

在普通的php中你可以这样做:

<?php 
$array=array ( 0 => 
   array ( 0 => array( roleID => 3, permID => 2 ), 
           1 => array ( roleID => 3 ,permID => 3 ),
           2 => array ( roleID => 2 ,permID => 4 ),
           3 => array ( roleID => 2 ,permID=> 5 ) ) );


    foreach($array as $allPermission) 

     foreach($array as $key=>$rolePermission)  

         if($allPermission->roleID==$rolePermission[$key]->permID) {  ?>

          <div class="perms">
            <input type="checkbox" name="permissions[]" id="<?php echo $allPermission->ID; ?>"  value="<?php print $allPermission->ID; ?>"  checked><?php print $allPermission->permName; ?></option></div>
         <?php } 

 ?>