开发者

PHP-ILooping an arrays values through a larger array

I want to know if it is possible to take an array and insert the array's values into a bigger array, multiple times, so that the values of the smaller array fill up the bigger array.

Say array1 has value开发者_高级运维s ([0 => 'a'],[1 => 'b'],[2 => 'c']), and array2 can hold 8 values. So, how would I take the values of array1 and insert them into array2 continuously until array2 runs out of space, so that array2 would have the values 'a','b','c','a','b','c','a','b'?

Thanks in advance, ~Hussain~


Essentially, you want to loop over and over the small array, adding each element to the new array until it has reached the desired size.

Consider this:

$max = 8;

$Orig_Array = array('a', 'b', 'c');
$Next_Array = array();

while True
{
    foreach($Orig_Array as $v)
    {
       $Next_Array[] = $v;
       if(count($Next_Array) >= $max)
          break 2;
    }
}


Assuming that your input array is indexed sequentially:

$len = count($input);
$output = array();
for ($i = 0; $i < MAX_SIZE; ++$i) 
  $output[] = $input[$i % $len];


$a = array('a','b','c');
$desired = 8;

$b = array();
for($i=0;$i<($desired/count($a))+1;++$i) $b = array_merge($b,$a);
array_splice($b,$desired);

Or

$a = array('a','b','c');
$desired = 8;

$b = array();
for($i=0;$i<$desired/count($a);++$i) $b = array_merge($b,$a);
for($i=0;$i<($desired-count($b)-1);++$i) $b[] = $a[$i];

The first one fills up an array so that it has at least desired number of elements and cuts off the rest. The second one fills up an array up the desired number of elements modulo original array size and adds up the rest.


Here's one using the input array's internal pointer, to keep things conceptually simple:

$input = array(1, 2, 3);
$size = 32;

$output = array();
for ( $i = 0; $i < $size; $i++ ) {
  $curr = current($input);
  if ( $curr === false ) {
    reset($input);
    $curr = current($input);
  }
  $output[] = $curr;
  next($input);
}

print_r($output);die;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜