【问题标题】:Repeat array to a certain length?将数组重复到一定长度?
【发布时间】:2010-08-29 16:54:49
【问题描述】:

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

【问题讨论】:

标签: php arrays repeat


【解决方案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】:

使用 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),但我认为这有点矫枉过正......

【讨论】:

  • 缺少一行:return $result;
  • @masakielastic 谢谢,已修复:)
  • 完整的迭代器解决方案太优雅了!
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    为了加入这个俱乐部:

    $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 的第二个参数,则长度相同)。

    【讨论】:

      【解决方案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】:

        如果你有 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】:
          <?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>';
          

          【讨论】:

          • $new_array 将以 72 个字符结尾。
          • 这只会创建可以被四除的数组(例如,如果将 end 设置为 73,它将生成大小为 76 的数组!
          • 这应该有效,但前提是您将“$end + 1”设置为长度不是从 0 开始的。如果您现在也用 array_merge() 替换您的 foreach 循环,您将拥有与我的答案完全相同的代码;)
          【解决方案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】:

              我认为 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);
              

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

              :)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-11-09
                • 2011-03-24
                • 1970-01-01
                • 1970-01-01
                • 2017-10-18
                • 2017-12-21
                • 1970-01-01
                • 2014-07-01
                相关资源
                最近更新 更多