doufen3786 2013-09-01 20:38
浏览 53
已采纳

均匀连续地合并多个阵列

Imagine having a few array structures (I present three, but I'd like to be as flexible as possible)

$array1 = array("red", "red", "red");  

$array2 = array("green", "green", "green", "green"); 

$array3 = array("blue", "blue"); 

I need to merge these arrays together and have a structure like so:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => red
    [4] => green
    [5] => blue
    [6] => red
    [7] => green
    [8] => green
)

The idea is to iterate through all arrays and merge elements one by one, if any of the arrays has run out of elements, the cycle should continue as normal, I'm not sure if I'm explaining myself the best here

  • 写回答

2条回答 默认 最新

  • dongyan5239 2013-09-01 20:44
    关注

    using count , array_push , and loop on counts

    <?php
    $array1 = array("red", "red", "red");  
    
    $array2 = array("green", "green", "green", "green"); 
    
    $array3 = array("blue", "blue"); 
    $ArrayLength = array(count($array1),count($array2),count($array3));
    $Arrays= array ( $array1,$array2,$array3 );
    
    
    $MergeArray=array();
    $flag=true;
    for($i=0;$flag==true;$i++)
    {
       $flag=false;
       for($j=0;$j < count($ArrayLength) ; j++)
       {      
           if( $i < $ArrayLength[$j] )
           {
              array_push( $MergeArray , $Arrays[$j][$i] );
              $flag=true;
           }
       }
    }
    Print_r(  $MergeArray );
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应