合并没有键的动态数组


Merge dynamic arrays without keys

我有两个数组:

$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。按钮组小部件示例:

<?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);

你试过吗:

$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']
        ]);
?>
您可以使用

array_merge() 方法在一行中执行此操作。

例:

echo ButtonGroup::widget([
        'buttons' => array_merge($array1, array2),
        'options' => ['class' => 'float-right']
    ]);