我有两个数组:
$array1 = ['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
$array2 = ['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
我想要做的是合并这些数组:
$array3 = [$array1, array2];
所以示例结果应该是这样的:
$array3 = [
['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']],
['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']]
];
我该怎么做?我正在使用Yii2框架和引导小部件ButtonGroup。 ButtonGroup小部件示例:
<?php
echo ButtonGroup::widget([
'buttons' => [
['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']],
['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']]
],
'options' => ['class' => 'float-right']
]);
?>
我需要合并这些数组的原因是因为我的ButtonGroup是动态的,而在视图文件中我想使用来自控制器$ buttonGroup的变量:
<?php
echo ButtonGroup::widget([
'buttons' => [$buttonGroup],
'options' => ['class' => 'float-right']
]);
?>
更新在控制器中我有:
$buttonGroups = [];
foreach($client as $key => $value) {
$buttonGroups[] = ['label' => $client[$key], 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
}
其中$client[$key]
是按钮的名称。所以我的数组是动态的,我不能像这样合并数组:
$array3 = array($array1, $array2);
答案 0 :(得分:0)
$array3 = array( $array1, $array2 );
然后:
echo ButtonGroup::widget([
'buttons' => $array3,
'options' => ['class' => 'float-right']
]);
<强>更新强>
[
['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']],
['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']]
]
只是(自PHP5.4起)的另一种定义风格:
从PHP 5.4开始,您还可以使用短数组语法,将array()替换为[]。
来源:http://php.net/manual/en/language.types.array.php
array(
array('label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']),
array('label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button'])
)
所以你应该可以直接使用:
<?php
echo ButtonGroup::widget([
'buttons' => $buttonGroups,
'options' => ['class' => 'float-right']
]);
?>
答案 1 :(得分:0)
您可以使用array_merge()
方法在一行中完成。
示例:
echo ButtonGroup::widget([
'buttons' => array_merge($array1, array2),
'options' => ['class' => 'float-right']
]);