[英]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.