重复阵列到一定长度? [英] Repeat array to a certain length?

查看:151
本文介绍了重复阵列到一定长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有例如,具有4元素阵列(A,B,C,D)的数组; 什么是最快的方法重复这个数组来创建一个新的数组具有一定的长度,例如71元?


解决方案

  //变量
$阵列=阵列(一,B,C,D);
$ desiredLength = 71;
$ newArray =阵列();
//通过在新阵列的端部接合的阵列创建新阵列与至少元件的所需数量的
而(计数($ newArray)LT = $ desiredLength){
    $ newArray = array_merge($ newArray,$阵列);
}
//减少新阵列到期望的长度(因为可能有新的数组中的元素过多
$阵列= array_slice($ newArray,0,$ desiredLength);

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?

解决方案

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

这篇关于重复阵列到一定长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆