2014-02-16 104 views
1

我有此数组:从一个阵列移动元素到另一个

$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' 
); 

我如何执行此操作 感谢

+0

究竟是什么问题? – jeroen

+0

我将如何执行此任务 – Arken

+0

到目前为止你有什么? – jeroen

回答

2

下面的代码应该成为你的目的:

$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

+2

亲爱的downvoter,我可以知道我的回答有什么问题吗? –

+1

太快判断和downvote,但从来没有提供可能会更好的答案 – AdRock

4

array_slice()会的$arr1第一X元素复制到$arr2,然后你可以使用array_diff_assoc()$arr1删除这些项目。第二个函数将比较键和值,以确保只删除适当的元素。

$x = 3; 
$arr2 = array_slice($arr1, 0, $x, true); 
$arr1 = array_diff_assoc($arr1, $arr2); 
相关问题