在 Twig 中循环两个数组
Loop over two arrays in Twig
我不知道你如何调用以下内容,但我的循环中需要一种模式。
假设我有 2 个数组。
Array1 = 1..10
Array2 = ['a','b','a','b','b']
我需要的结果应该是:
1a,
2b,
3a,
4b,
5b,
6a,
7b,
8a,
9b,
10b
如何使用 Twig 模板实现此目的?
您可以尝试使用 modulo 算法,例如(C# code):
// result array will be max of Array1 and Array2 lengths
string[] Array3 = new string[Math.Max(Array1.Length, Array2.Length)];
// Note Array1[i % Array1.Length] and Array2[i % Array2.Length]
// index of each array (Array1, Array2) is remainder of Array1.Length or Array2.Length
// So i % Array1.Length will be 0, 1, ..., Array1.Length, 0, 1, 2 etc
for (int i = 0; i < Array3.Length; ++i)
Array3[i] = $"{Array1[i % Array1.Length]}{Array2[i % Array2.Length]}";
// Let's have a look at Array3:
Console.Write(string.Join(", ", Array3));
在JavaScript
中使用modulo
:
const _getArr = (from, to, chars) => {
const res = [];
const len = chars.length;
let count = 0;
for (let i = from; i <= to; i++) {
console.log(count, count%len, chars[count % len]);
res[count] = `${i}${chars[count % len]}`;
count++;
}
return res;
}
console.log( _getArr(1, 10, ['a','b','a','b','b']) );
我不知道你如何调用以下内容,但我的循环中需要一种模式。
假设我有 2 个数组。
Array1 = 1..10
Array2 = ['a','b','a','b','b']
我需要的结果应该是:
1a,
2b,
3a,
4b,
5b,
6a,
7b,
8a,
9b,
10b
如何使用 Twig 模板实现此目的?
您可以尝试使用 modulo 算法,例如(C# code):
// result array will be max of Array1 and Array2 lengths
string[] Array3 = new string[Math.Max(Array1.Length, Array2.Length)];
// Note Array1[i % Array1.Length] and Array2[i % Array2.Length]
// index of each array (Array1, Array2) is remainder of Array1.Length or Array2.Length
// So i % Array1.Length will be 0, 1, ..., Array1.Length, 0, 1, 2 etc
for (int i = 0; i < Array3.Length; ++i)
Array3[i] = $"{Array1[i % Array1.Length]}{Array2[i % Array2.Length]}";
// Let's have a look at Array3:
Console.Write(string.Join(", ", Array3));
在JavaScript
中使用modulo
:
const _getArr = (from, to, chars) => {
const res = [];
const len = chars.length;
let count = 0;
for (let i = from; i <= to; i++) {
console.log(count, count%len, chars[count % len]);
res[count] = `${i}${chars[count % len]}`;
count++;
}
return res;
}
console.log( _getArr(1, 10, ['a','b','a','b','b']) );