Repeat array to a certain length?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

I'm having an array for example with 4 elements array("a", "b", "c", d"); what is the fastest way to repeat this array to create a new array with a certain length, e.g 71 elements?

回答1:

// the variables $array = array("a", "b", "c", "d"); $desiredLength = 71; $newArray = array(); // create a new array with AT LEAST the desired number of elements by joining the array at the end of the new array while(count($newArray) <= $desiredLength){     $newArray = array_merge($newArray, $array); } // reduce the new array to the desired length (as there might be too many elements in the new array $array = array_slice($newArray, 0, $desiredLength); 


回答2:

Solution using SPL InfiniteIterator:

<?php function fillArray1($length, $values) {     foreach (new InfiniteIterator(new ArrayIterator($values)) as $element) {         if (!$length--) return $result;         $result[] = $element;     }     return $result; }  var_dump(fillArray(71, array('a', 'b', 'c', 'd'))); 

The real SPL hackers might have dropped the if (!$length--) break; and instead used a limit iterator: new LimitIterator(new InfiniteIterator(new ArrayIterator($values)), 0, $length), but I thought that to be overkill...



回答3:

In order to join this club:

$result = call_user_func_array('array_merge', array_fill(0, ceil($size/count($array)), $array)); while(count($result) > $size) array_pop($result); 

You asked for the fastest so I did a benchmark (Source: http://pastebin.com/G5w7QJPU)

Kau-Boy: 5.40128803253 Frxstrem: 5.00970411301 NikiC: 4.12150001526 user2469998: 0.561513900757 Alexander: 1.92847204208 Hammerite: 2.17130494118 Max: 12.9516701698 Evert: 1.9378361702 Christoph: 1.6862449646 Test took 35.7696909904s 

user2469998 is the fastest but it only works for string values with single chars (or the same length if you use second parameter of str_split).



回答4:

A simple solution using each() and reset() and the array's internal pointer:

<?php $array = array('a', 'b', 'c', 'd'); $length = 71; $result = array(); while(count($result) < $length) {   $current = each($array);   if($current == false)   {     reset($array);     continue;   }   $result[] = $current[1]; }  echo count($result); // Output: 71 


回答5:

$newarray = array(); $i = 0; $oldarrayvalues = array_values($oldarray); $oldarraysize = count($oldarrayvalues); if ( $oldarraysize ) {     while ( count($newarray) < DESIRED_ARRAY_SIZE ) {         $newarray[] = $oldarrayvalues[$i];         $i++;         $i %= $oldarraysize;     } } 


回答6:

If you have PHP 5.3 available, you can also try this:

function fill(array $initalArray, $toCount) {     $initialArrayCount = count($initalArray);      $fillUp = function(array $filledUpArray, $missingCount)                      use(&$fillUp, $initalArray, $initialArrayCount, $toCount)      {         if($missingCount <= 0) return array_slice($filledUpArray, 0, $toCount);         return $fillUp(array_merge($filledUpArray, $initalArray), $missingCount - $initialArrayCount);     };      return $fillUp($initalArray, $toCount - $initialArrayCount); }   $theArray = array("a", "b", "c", "d"); $toLength = 71;  $filledArray = fill($theArray, $toLength);  print_r($filledArray); 


回答7:

<?php $array = array('a', 'b', 'c', 'd'); $end   = 71;  $new_array = array();  while(count($new_array) <= $end) {     foreach($array as $key => $value)     {         $new_array[] = $value;     } }  $new_array = array_slice($new_array, 0, $end); 

Tested and works.

You can test for yourself by adding this:

echo '<pre>'; print_r($new_array); echo '</pre>'; 


回答8:

$array = array("a", "b", "c", "d"); $merge = array(); $desiredLength = 71; while(2 * count($array) <= $desiredLength){     $array = array_merge($array, $array); } if($desiredLength > count($array))     $merge = array_slice($array, 0, $desiredLength - count($array)); $array = array_merge($array, $merge); $array = array_slice($array, 0, $desiredLength); print_r($array); 


回答9:

$arr = array("a", "b", "c", "d"); $len = 71; $a = array(); $a = str_split( substr( str_repeat( join( $arr), ceil( $len / count( $arr))), 0, $len)); var_export($a); 


回答10:

I think that user2469998 was closest but just not that nice.

For my example, I use pipe to implode and the str_repeat function to build a string that meets the length, explode it back apart and trim the fat.

$list = array('a','b','c','d');  $length = 6;  $result = array_slice(explode('|', str_repeat(implode('|', $list).'|',ceil($length/count($list)))), 0, $length); 

Many ways to achieve this but thought I'd share mine. The only restriction is that you need to use a character to implode and explode on which isn't part of the array items or the exploder won't work properly.

:)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!