重复数组到一定长度?

发布于 2024-09-16 07:27:37 字数 102 浏览 6 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

千里故人稀 2024-09-23 07:27:37
// 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);
// 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);
筑梦 2024-09-23 07:27:37

使用 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')));

真正的 SPL 黑客可能已经删除了 if (!$length--) break; 并使用限制迭代器:new LimitIterator(new InfiniteIterator(new ArrayIterator($values)), 0, $length),但我认为这太过分了...

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

聚集的泪 2024-09-23 07:27:37

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

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
笑红尘 2024-09-23 07:27:37

为了加入这个俱乐部:

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

你要求最快,所以我做了一个基准测试(来源: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 是最快的,但它仅适用于具有单个字符的字符串值(或者如果使用 str_split 的第二个参数,则长度相同)。

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

屌丝范 2024-09-23 07:27:37
$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;
    }
}
$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;
    }
}
沉默的熊 2024-09-23 07:27:37

如果您有可用的 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);

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);
花开半夏魅人心 2024-09-23 07:27:37
<?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);

经过测试并有效。

您可以通过添加以下内容自行测试:

echo '<pre>';
print_r($new_array);
echo '</pre>';
<?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>';
疯了 2024-09-23 07:27:37
$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);
$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);
爱她像谁 2024-09-23 07:27:37
$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);
$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);
预谋 2024-09-23 07:27:37

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

对于我的示例,我使用管道进行内爆,并使用 str_repeat 函数构建一个满足长度的字符串,将其分解并修剪脂肪。

$list = array('a','b','c','d');

$length = 6;

$result = array_slice(explode('|', str_repeat(implode('|', $list).'|',ceil($length/count($list)))), 0, $length);

有很多方法可以实现这一目标,但我想分享一下我的方法。唯一的限制是您需要使用不属于数组项的角色进行内爆和爆炸,否则爆炸器将无法正常工作。

:)

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.

:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文