2014-02-16 102 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); 
相關問題