I have two arrays:
$array1 = ['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
$array2 = ['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
What I want to do, is to merge these arrays like this:
$array3 = [$array1, array2];
So example result whould be like this:
$array3 = [
['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']],
['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']]
];
How can I do that? I'm using Yii2 framework, and bootstrap widget ButtonGroup. ButtonGroup widget example:
<?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']
]);
?>
The reason I need to merge these arrays like this is because my ButtonGroup is dynamic, and in view file I want to use variable from controller $buttonGroup:
<?php
echo ButtonGroup::widget([
'buttons' => [$buttonGroup],
'options' => ['class' => 'float-right']
]);
?>
Update In controller I have this:
$buttonGroups = [];
foreach($client as $key => $value) {
$buttonGroups[] = ['label' => $client[$key], 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']];
}
where $client[$key]
is the name of the button. So my arrays are dynamic and I can't just merge arrays like this:
$array3 = array($array1, $array2);
did you try:
$array3 = array( $array1, $array2 );
and then :
echo ButtonGroup::widget([
'buttons' => $array3,
'options' => ['class' => 'float-right']
]);
Update:
[
['label' => 'FirstButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']],
['label' => 'SecondButton', 'options' => ['class' => 'btn btn-sm btn-default', 'type' => 'button']]
]
is simply another definition style of (since PHP5.4):
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
Source: 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'])
)
so you should be able to use directly:
<?php
echo ButtonGroup::widget([
'buttons' => $buttonGroups,
'options' => ['class' => 'float-right']
]);
?>
You can do it in a single line using the array_merge()
method.
Example:
echo ButtonGroup::widget([
'buttons' => array_merge($array1, array2),
'options' => ['class' => 'float-right']
]);