【问题标题】:Move element from one array to another [closed]将元素从一个数组移动到另一个[关闭]
【发布时间】:2014-02-16 01:07:48
【问题描述】:

我有这个数组:

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

如何执行此操作 谢谢

【问题讨论】:

  • 究竟是什么问题?
  • 我将如何执行此任务
  • 到目前为止你有什么?
  • 这是一个非常直接的问题,我自己也有。
  • @JasonBasanese 如果您有兴趣,我已经用更优雅的方式更新了答案中的代码。使用 PHP 已经 14 年了,但有时我看到我几年前写的东西,想知道我在想什么。

标签: php arrays associative-array


【解决方案1】:

以下代码应该可以满足您的目的:

$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】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2017-07-11
    • 2015-03-07
    • 2011-07-15
    • 2020-07-29
    相关资源
    最近更新 更多