您好我正在创建一个数组,它将在我的网站中存储部分。其中一些部分将无法供某些用户查看,因此我需要在放入我的阵列之前检查相关用户的权限。但是当我这样做时,如果语句我得到一个我不想要的数组中的数组,这会导致以下错误:
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"
}
}
答案 0 :(得分:1)
再创建一个
$this->sections = ['Projects' => $restrictsections];
$this->sections['Projects']['View'] = route('project.index');
答案 1 :(得分:1)
您可以使用+
运算符组合数组。
例如:
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
];
编辑:+
在技术上是一个联合,所以如果第二个数组具有第一个数组中存在的键,它们将被忽略。
答案 2 :(得分:1)
像这样使用array_merge()
$this->sections = [
'Projects' => array_merge(
['View' => route('project.index')],
$restrictsections
)
];
或像这样使用+
运算符
$this->sections = [
'Projects' => ['View' => route('project.index')] + $restrictsections
];