本文介绍了如何在特定位置将元素插入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有两个数组:
$array_1 = 数组('0' =>'零','1' =>'一','2' =>'二','3' =>'三',);$array_2 = 数组('零' =>'0','一个' =>'1','两个' =>'2','三' =>'3',);
现在,我想在每个数组的第三个元素之后插入 array('sample_key' => 'sample_value')
.我该怎么做?
解决方案
array_slice()
可用于提取数组的一部分,联合数组运算符(+
) 可以重新组合部分.
$res = array_slice($array, 0, 3, true) +数组("my_key" => "my_value") +array_slice($array, 3, count($array)-3, true);
这个例子:
$array = array('零' =>'0','一个' =>'1','两个' =>'2','三' =>'3',);$res = array_slice($array, 0, 3, true) +数组("my_key" => "my_value") +array_slice($array, 3, count($array) - 1, true) ;打印_r($res);
给出:
大批([零] => 0[一] => 1[二] => 2[my_key] => my_value[三] => 3)Let's imagine that we have two arrays:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
Now, I'd like to insert array('sample_key' => 'sample_value')
after third element of each array. How can I do it?
解决方案
array_slice()
can be used to extract parts of the array, and the union array operator (+
) can recombine the parts.
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);
This example:
$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);
gives:
Array ( [zero] => 0 [one] => 1 [two] => 2 [my_key] => my_value [three] => 3 )
这篇关于如何在特定位置将元素插入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!