数组项与循环

时间:2015-12-18 22:16:31

标签: php

我正在努力处理循环处理中的一些循环。我想在$ items数组的每3项之后输出$ additional数组的一个增量项。另外,当我们到达$ items数组中的item-15时,我想再次使用$ additional数组从extra-1开始。


$items = array(
    "item-1",
    "item-2",
    "item-3",

    "item-4",
    "item-5",
    "item-6",

    "item-7",
    "item-8",
    "item-9",

    "item-10",
    "item-11",
    "item-12",

    "item-13",
    "item-14",
    "item-15",
);

$additional = array(
    "extra-1",
    "extra-2",
    "extra-3",
    "extra-4",
);

最后我想结束这样的事情:

    "item-1",
    "item-2",
    "item-3",
"extra-1",
    "item-4",
    "item-5",
    "item-6",
"extra-2",
    "item-7",
    "item-8",
    "item-9",
"extra-3",
    "item-10",
    "item-11",
    "item-12",
"extra-4",
    "item-13",
    "item-14",
    "item-15",
"extra-1"

我尝试了一些不同循环(for,foreach和while)与不同计数器组合的东西。

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

以下代码完成了这项工作:

$length = count($items);
$additionalLength = count($additional);
for ($i = 1; $i <= $length; ++$i) {
    echo $items[$i - 1] . "\n";
    if ($i % 3 === 0) {
        echo $additional[(($i / 3) - 1) % $additionalLength] . "\n";
    }
}

答案 1 :(得分:0)

这是我的解决方案,非常难看,但它确实有效!

$counter = 0;
$first_value = 0;
foreach ($items as $values) {
    $temp[] = $values;
    $counter++;
    if ($counter % 3 == 0 && count($additional) != 0) {
        $first_value ? $temp[] = array_shift($additional) : $extra1 = array_shift($additional);
        $first_value ?: $temp[] = $extra1;
        $first_value = 1;
    }
}
$temp[] = $extra1;