关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。
想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。
7年前关闭。
Improve this question
我有这个数组:
$arr1 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2',
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);
我想要做的是取前 3 个元素,删除它们并用它们创建一个新数组。
所以你会有这个:
$arr1 = array(
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);
$arr2 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2'
);
我如何执行此操作
谢谢
最佳答案
以下代码应符合您的目的:
$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
)
Demo
关于php - 将元素从一个数组移动到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805954/