我正在尝试根据数组元素的值重复输出该值一定次数。我有以下两个数组:
<?php
$a = array(1, 2, 3);
$b = array(3, 2, 5);
foreach ($b as $x) {
for ($i = 1; $i <= $x; $i++) {
echo $a[$i-1]; // 修改为输出 $a 数组对应索引的值,而非打印 $i
}
}
然而,上述代码尚未实现您期望的功能。您想要的输出是基于 $a
数组的值进行重复,而重复次数由 $b
数组中的相应元素决定。以下是修正后的代码:
<?php
$a = array(1, 2, 3);
$b = array(3, 2, 5);
$result = '';
$index = 0;
foreach ($b as $repeatCount) {
for ($i = 1; $i <= $repeatCount; $i++) {
if ($index < count($a)) {
$result .= $a[$index];
}
// 避免数组越界
}
$index++;
}
echo $result; // 输出:111223333
这样应该可以得到您期望的输出结果 111223333