将元素从一个数组移动到另一个数组

时间:2014-02-16 01:07:48

标签: php arrays associative-array

我有这个数组:

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

我该如何执行此操作 感谢

2 个答案:

答案 0 :(得分:4)

array_slice()会将$arr1的第一个 x 元素复制到$arr2,然后您可以使用array_diff_assoc()从{{0}}删除这些项目{1}}。第二个函数将比较键和值,以确保仅删除相应的元素。

$arr1

答案 1 :(得分: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