Move element from one array to another [closed]

青春壹個敷衍的年華 提交于 2019-12-13 20:04:32

问题


I have this array:

$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.

So you would have this:

$arr1 = array(
  '54' => 'sdfsdf2',
  '53' => '2ssdf',
  '62' => 'sfds'
);

$arr2 = array(
  '76' => '1sdf',
  '43' => 'sdf2',
  '34' => 'sdf2'
);

How can I perform this action Thanks


回答1:


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

The output will be:

Array
(
    [54] => sdfsdf2
    [53] => 2ssdf
    [62] => sfds
)
Array
(
    [76] => 1sdf
    [43] => sdf2
    [34] => sdf2
)

Demo




回答2:


array_slice() will copy the first x elements of $arr1 into $arr2, and then you can use array_diff_assoc() to remove those items from $arr1. The second function will compare both keys and values to ensure that only the appropriate elements are removed.

$x    = 3;
$arr2 = array_slice($arr1, 0, $x, true);
$arr1 = array_diff_assoc($arr1, $arr2);


来源:https://stackoverflow.com/questions/21805954/move-element-from-one-array-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!