douzhi1879 2018-06-08 10: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 10: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++;
            }
        }
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部