将元素从一个数组移到另一个数组 [英] Move element from one array to another
本文介绍了将元素从一个数组移到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
$arr1 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2',
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);
我想做的是获取前三个元素,将其删除,并使用它们创建一个新的数组.
What I want to do is take the first 3 elements, remove them and create a new array with them.
所以您会得到这个:
$arr1 = array(
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);
$arr2 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2'
);
我如何执行此操作 谢谢
How can I perform this action Thanks
推荐答案
以下代码应达到您的目的:
The following code should serve your purpose:
$arr1 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2',
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
); // the first array
$arr2 = array(); // the second array
$num = 0; // a variable to count the number of iterations
foreach($arr1 as $key => $val){
if(++$num > 3) break; // we don’t need more than three iterations
$arr2[$key] = $val; // copy the key and value from the first array to the second
unset($arr1[$key]); // remove the key and value from the first
}
print_r($arr1); // output the first array
print_r($arr2); // output the second array
输出将是:
Array
(
[54] => sdfsdf2
[53] => 2ssdf
[62] => sfds
)
Array
(
[76] => 1sdf
[43] => sdf2
[34] => sdf2
)
这篇关于将元素从一个数组移到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文