douzhi1879 2018-06-08 18:22
浏览 259
已采纳

array_push使用索引并随机插入另一个数组

I have two arrays like

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

$second = 

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

But, I want to push the second array elements into the first array by index. like

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

without changing the first elements order.help me please

  • 写回答

1条回答 默认 最新

  • doulan8054 2018-06-08 18:30
    关注

    You can, make a simple loop:

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

    If your array have variable size, compare their size first and do the loop with the bigger count.

    EDIT:

    Then taking in account you want to conserve their respective order, but merge randomly the arrays you could twist the previous code that way:

    $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];}
        }
    }
    

    I admit it's very weird and twisted and I'm sure something more optimized could be made (it's done quickly), but, the question itself is weird xD I hope it will help :)

    EDIT 2:

    In fact the first edit will only alternate A/B, for a full random solution and still respecting the respective order of both arrays:

    $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++;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示