簡體   English   中英

php laravel array_merge鍵值

[英]php laravel array_merge key value

嗨,我正在創建一個數組,它將在我的網站中存儲部分。 這些部分中的某些部分將對某些用戶不可用,因此在放入陣列之前,我需要檢查相關用戶的許可。 但是,當我執行此if語句時,我在不需要的數組中得到一個數組,這會導致以下錯誤:

Method Illuminate\\View\\View::__toString() must not throw an exception

這是我正在使用的代碼:

$user = Auth::user(); 
 if(($user->hasRole('Admin') || $user->hasRole('Admin') || $user->hasRole('Project Master') || $user->hasRole('Project Owner'))) {
  $restrictsections = ['Create' => route('project.create'),
                       'Sort' => route('project.sort'),];
  }

$this->sections = [
    'Projects' => [
        'View' => route('project.index'),
        $restrictsections

    ]
];

現在,數組的結構如下:

array(1) {
  ["Projects"]=>
  array(2) {
    ["Create"]=>
    string(30) "http://projects.local/projects"
    [0]=>
    array(2) {
      ["Create"]=>
      string(37) "http://projects.local/projects/create"
      ["Edit"]=>
      string(35) "http://projects.local/projects/sort"
    }
  }
}

相對於:

  $this->sections = [
        'Project' => [
            'View' => route('project.index'),
            'Create' => route('project.create'),
             'Sort' => route('project.sort'),
        ]
    ];


array(1) {
  ["Project"]=>
  array(3) {
    ["View"]=>
    string(30) "http://projects.local/project"
    ["Create"]=>
    string(37) "http://projects.local/project/create"
    ["Sort"]=>
    string(35) "http://projects.local/project/sort"
  }
}

有什么想法可以將兩個數組合並在一起嗎? 但其結構應如下:

array(1) {
  ["Project"]=>
  array(3) {
    ["View"]=>
    string(30) "http://projects.local/project"
    ["Create"]=>
    string(37) "http://projects.local/project/create"
    ["Sort"]=>
    string(35) "http://projects.local/project/sort"
  }
}

再創建一個

$this->sections = ['Projects' =>  $restrictsections];
$this->sections['Projects']['View'] = route('project.index');

您可以使用+運算符組合數組。

例如:

php > print_r(['View' => '1'] + ['Create' => 'two', 'Sort' => '3']);
Array
(
    [View] => 1
    [Create] => two
    [Sort] => 3
)

適用於您的代碼:

$user = Auth::user(); 
 if(($user->hasRole('Admin') || $user->hasRole('Admin') || $user->hasRole('Project Master') || $user->hasRole('Project Owner'))) {
  $restrictsections = ['Create' => route('project.create'),
                       'Sort' => route('project.sort'),];
  }

$this->sections = [
    'Projects' => [
        'View' => route('project.index')
    ] + $restrictsections
];

編輯: +從技術上講是一個並集,因此,如果第二個數組中的鍵出現在第一個數組中,則將忽略它們。

像這樣使用array_merge()

$this->sections = [
    'Projects' => array_merge(
        ['View' => route('project.index')],
        $restrictsections
    )
];

或像這樣使用+運算符

$this->sections = [
    'Projects' => ['View' => route('project.index')] + $restrictsections
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM