如何将php数组插入到另一个数组中


How to insert a php array into another array

来自javascript背景,在将php数组插入另一个数组时遇到了一些困难。

如果我有以下内容:

$common_properties = array(
    'foo' => 'bar',
    'eats' => array(
        'apples' => true,
        'oranges' => true
    )
);
$one = array(
    'name' => 'one',
    'desc' => 'Lorem'
);
$two = array(
    'name' => 'two',
    'desc' => 'Ipsum'
);

如何从$one$two访问$common_properties阵列?我需要将结果数组作为参数传递给函数。由于某种原因,array_merge导致了一个错误。

期望的结果应该是,例如:

$one = array(
    'name' => 'one',
    'desc' => 'Lorem'
    'foo' => 'bar',
    'eats' => array(
        'apples' => true,
        'oranges' => true
    )
);
$one = array_merge($one, $common_properties);
print_r($one);
/* ⇨
Array
(
    [name] => one
    [desc] => Lorem
    [foo] => bar
    [eats] => Array
        (
            [apples] => 1
            [oranges] => 1
        )
)
*/

您可以执行以下操作将$common_properties添加到$one$two

$one['commonProperties'] = $common_properties;

$two['commonProperties'] = $common_properties;

然后,您可以将两个数组($one$two)传递给您的方法,如function_name($one, $two)