重复数组到一定的长度?

时间:2022-04-22 21:45:53

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?

我有一个数组,例如4个元素数组(“a”,“b”,“c”,d“);重复此数组以创建具有一定长度的新数组的最快方法是什么,例如71元素?

10 个解决方案

#1


8  

// 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


3  

Solution using SPL InfiniteIterator:

使用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...

真正的SPL黑客可能已经放弃了if(!$ length--)休息时间;而是使用了一个限制迭代器:新的LimitIterator(新的InfiniteIterator(新的ArrayIterator($ values)),0,$ length),但我认为这有点过分...

#3


2  

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)

你要求最快,所以我做了一个基准测试(来源: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).

user2469998是最快的,但它仅适用于具有单个字符的字符串值(如果使用str_split的第二个参数,则相同的长度)。

#4


1  

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

使用each()和reset()以及数组的内部指针的简单解决方案:

<?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


0  

$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


0  

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

如果你有PHP 5.3,你也可以试试这个:

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


0  

<?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


0  

$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


0  

$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


0  

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

我认为user2469998最接近,但不是那么好。

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.

对于我的例子,我使用管道内爆和str_repeat函数来构建一个符合长度的字符串,将它分开并将其修剪掉。

$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.

实现这一目标的方法很多,但我想我会分享我的。唯一的限制是你需要使用一个字符进行内爆和爆炸,这不是数组项的一部分,否则爆炸将无法正常工作。

:)

:)

#1


8  

// 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


3  

Solution using SPL InfiniteIterator:

使用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...

真正的SPL黑客可能已经放弃了if(!$ length--)休息时间;而是使用了一个限制迭代器:新的LimitIterator(新的InfiniteIterator(新的ArrayIterator($ values)),0,$ length),但我认为这有点过分...

#3


2  

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)

你要求最快,所以我做了一个基准测试(来源: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).

user2469998是最快的,但它仅适用于具有单个字符的字符串值(如果使用str_split的第二个参数,则相同的长度)。

#4


1  

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

使用each()和reset()以及数组的内部指针的简单解决方案:

<?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


0  

$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


0  

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

如果你有PHP 5.3,你也可以试试这个:

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


0  

<?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


0  

$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


0  

$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


0  

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

我认为user2469998最接近,但不是那么好。

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.

对于我的例子,我使用管道内爆和str_repeat函数来构建一个符合长度的字符串,将它分开并将其修剪掉。

$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.

实现这一目标的方法很多,但我想我会分享我的。唯一的限制是你需要使用一个字符进行内爆和爆炸,这不是数组项的一部分,否则爆炸将无法正常工作。

:)

:)