2017-03-03 83 views
0

我有一個這樣的數組:推多了一個元素數組PHP

return array(

    'User Management -> Role Management' => array(
     array(
      'permission' => 'role-management.view', 
      'label'  => 'View', 
     ), 
     array(
      'permission' => 'role-management.create', 
      'label'  => 'Create', 
     ), 
     array(
      'permission' => 'role-management.edit', 
      'label'  => 'Edit', 
     ), 
     array(
      'permission' => 'role-management.delete', 
      'label'  => 'Delete', 
     ), 
    ), 

    'User Management -> User Management' => array(
     array(
      'permission' => 'user-management.view', 
      'label'  => 'View', 
     ), 
     array(
      'permission' => 'user-management.create', 
      'label'  => 'Create', 
     ), 
     array(
      'permission' => 'user-management.edit', 
      'label'  => 'Edit', 
     ), 
     array(
      'permission' => 'user-management.delete', 
      'label'  => 'Delete', 
     ), 
    ), 

); 

我已經成功地訪問該數組像這樣:

$permissions = Config::get('permissions'); 

我想補充以下label新指標。我已經嘗試過,但無法添加。 `的foreach($權限$許可){

 foreach ($permission as $eachPermission) { 

      $encodedPermission = base64_encode($eachPermission['permission']); 

      // $eachPermission['encodedPermission'] = $encodedPermission; 
      array_push($eachPermission, "encodedPermission", $encodedPermission);    
     } 
    } 
    var_dump($permissions); ` 

我嘗試了這些,但不能設置新的索引。我的預期結果是這樣的:

'permission' => 'role-management.view', 
'label'  => 'View', 
'encodedPermission' => 'someencodedstring' 

我是做錯了還是錯過了一些東西。

回答

1

您的數組是多層次的,所以您需要進行雙向foreach才能達到更改所需的級別。

並且爲了將您的更改保存在原始數組中,您需要在迭代器之前使用與號(&)以保持對原始數組的引用。沒有它,你只會將新數據插入到爲foreach循環創建的數組副本中。

這工作:

foreach ($permissions as &$eachPermission) { 
    foreach ($eachPermission as &$singlePermission) { 
     $encodedPermission = base64_encode($singlePermission['permission']); 
     array_push($singlePermission, "encodedPermission", $encodedPermission); 
    } 
} 
var_dump($permissions); 
1

我會做這樣的,只是因爲它是更容易理解......

foreach($permissions as $name1=>$ar1){ 
    foreach($ar1 as $name2=>$ar2){ 
     $permissions[$name1][$name2]['encodedPermission'] = base64_encode($ar2['permission']); 
    } 
}