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

标签 php arrays associative-array

关闭。这个问题不满足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/

相关文章:

php - 将一个mysql表内容从一台服务器复制到另一台服务器

C++ OpenGL 大型网格缺少三角形

arrays - 将数组添加到数组而不创建二维数组

java - Camera 对象上的 setOneShotPreviewCallback(),预览图像的裁剪版本

php - 打印关联数组时出错(错误 :unexpected "", 需要 T_STRING 或 T_NUM STRING)

php - 从jquery动态表中获取数组中的所有输入值

php - 在表中搜索以查找 set_id 是否存在 IP 地址

php - 如何使用 select 语句在 php 和 mysql 中获取最新的日期和时间

javascript - 访问对象内部的关联数组

Java 哈希表和 HashMap