【问题标题】:array_push using index and random inserting into another arrayarray_push 使用索引和随机插入另一个数组
【发布时间】:2018-11-18 20:33:16
【问题描述】:

我有两个类似的数组

$first = 
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
  [5] => 6
)

$second = 

Array
(
  [0] => apples
  [1] => organges
  [2] => bananas
  [3] => peaches
)

但是,我想通过索引将第二个数组元素推入第一个数组。 喜欢

$result = 
Array
(
  [0] => 1
  [1] => apples
  [2] => 2
  [3] => organges
  [4] => 3
  [5] => 4
  [6] => peaches
  [7] => 5
  [8] => 6
)

不改变第一个元素的顺序。请帮帮我

【问题讨论】:

标签: php


【解决方案1】:

你可以,做一个简单的循环:

$result = [];
for($i=0; $i < count($first); $i++) {
    if(isset($first[$i])){$result[] = $first[$i];}
    if(isset($second[$i])){$result[] = $second[$i];}
}

如果您的数组具有可变大小,请先比较它们的大小,然后使用更大的计数进行循环。

编辑:

然后考虑到您希望保留它们各自的顺序,但随机合并数组,您可以通过这种方式扭曲之前的代码:

$result = [];
for($i=0; $i < count($first); $i++) {
    if(rand(0,1)) {
        if(isset($first[$i])){$result[] = $first[$i];}
        if(isset($second[$i])){$result[] = $second[$i];}
    } else {
        if(isset($second[$i])){$result[] = $second[$i];}
        if(isset($first[$i])){$result[] = $first[$i];}
    }
}

我承认这很奇怪和扭曲,我确信可以做出更优化的东西(它很快就完成了),但是,问题本身很奇怪 xD 我希望它会有所帮助:)

编辑 2:

事实上,第一次编辑只会交替 A/B,以获得完全随机的解决方案,并且仍然尊重两个数组的各自顺序:

$result = [];
$end=count($first) + count($second);
$a=0;
$b=0;
for($i=0; $i < $end; $i++ {
    if(rand(0,1)) {
        if(isset($first[$a])) {
            $result[] = $first[$a];
            $a++;
        } elseif (isset($second[$b])) {
            $result[] = $second[$b];
            $b++;
        }
    } else {
        if(isset($second[$b])) {
            $result[] = $second[$b];
            $b++;
        } elseif (isset($first[$a])) {
            $result[] = $first[$a];
            $a++;
        }
    }
}

【讨论】:

  • OP 希望第二个数组随机固定在第一个数组上; "我想像结果数组一样将第二个数组元素随机推送到第一个数组中"
  • @WizardNx 不错。但是,我想每次都更改索引
  • 哦,如果我理解得很好,您想要交替源数组但总是以增量方式,对吗?
  • @GrumpyCrouton 检查编辑 :) 我想你会完成你的工作
猜你喜欢
  • 1970-01-01
  • 2017-12-24
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多