我有一个返回像这样的数组的函数
Array
(
[0] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
[1] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
)
我需要将上面的每个元素添加到另一个数组中,如此
Array
(
[0] => Array
(
[name] => Name
[value] => Johan
)
[1] => Array
(
[name] => Address
[value] => Mayfair Lane
)
)
问题是我需要在第二个数组的第一个和第二个元素之间插入第二个数组IN IN MIDDLE的第一个数组元素。
Array
(
[0] => Array
(
[name] => Name
[value] => Johan
)
[1] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
[2] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
)
[3] => Array
(
[name] => Address
[value] => Mayfair Lane
)
)
问题是,如果我只是按原样添加第一个数组,在中心(使用自己的变量),它就像这样添加
Array
(
[0] => Array
(
[name] => Name
[value] => Johan
)
[1] => Array
(
[0] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
[1] => Array
(
[name] => Percent
[attributes] => Array
(
[Percent] => 50
)
)
)
[2] => Array
(
[name] => Address
[value] => Mayfair Lane
)
)
我看过array_merge
但是当然,我无法指定第二个数组元素在我需要的中间位置。
答案 0 :(得分:1)
你需要array_splice(),例如:
array_splice($ second,1,0,$ first);
答案 1 :(得分:1)
您不需要进行循环。将它们拆分为2.合并第一部分,即要插入的中间部分,第二部分。
$arr1 = array(
array(
'name' => 'Percent',
'attributes' => array('Percent'=>50)
),
array(
'name' => 'Percent',
'attributes' => array('Percent'=>50)
)
);
$arr2 = array(
array(
'name'=>'Name',
'value'=>'Johan'
),
array(
'name'=>'Address',
'value'=>'Mayfair Lane'
)
);
$mid = count($arr2)/2;
$chunks = array_chunk($arr2, $mid);
$merged = array_merge($chunks[0], $arr1, $chunks[1]);
var_dump($merged);
RESULT
array(4) {
[0]=>
array(2) {
["name"]=>
string(4) "Name"
["value"]=>
string(5) "Johan"
}
[1]=>
array(2) {
["name"]=>
string(7) "Percent"
["attributes"]=>
array(1) {
["Percent"]=>
int(50)
}
}
[2]=>
array(2) {
["name"]=>
string(7) "Percent"
["attributes"]=>
array(1) {
["Percent"]=>
int(50)
}
}
[3]=>
array(2) {
["name"]=>
string(7) "Address"
["value"]=>
string(12) "Mayfair Lane"
}
}