环绕字符串的简单循环不起作用?

simple loop that wraps around string not working?

基本上,我想生成任意长度的音符串,例如从 A 到 G,在 G 之后自然环绕到另一个八度音阶的 A。到目前为止,我有这个:

function generateNotes($start, $numbers) {
    $notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

    $indice = array_search($start, $notes);

    foreach (range(0, $numbers-1) as $number) {
    
        
        if(($number + $indice) >= count($notes)) {
                $number -= count($notes);
        } 
        
        echo ($number + $indice) . " ";
        
    }

}

echo generateNotes('E', 24);

我得到的是以下内容,这让我感到困惑:

4 5 6 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

它第一次工作,6(是 G)环绕到 0(A),但是下一次(数字 + 索引)> 6 它再也不会工作了。为什么它只在循环中的第一次起作用?

您的问题是您试图在 foreach 内的 if 块中分配 $number,但在每个循环结束时,[=12= 的值] 再次被 foreach 覆盖,所以你所做的没有任何效果。只使用模运算更容易:

function generateNotes($start, $numbers) {
    $notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
    $num_notes = count($notes);
    $indice = array_search($start, $notes);

    foreach (range(0, $numbers-1) as $number) {
        echo (($number + $indice) % $num_notes) . " ";
    }
}

echo generateNotes('E', 24);

输出:

4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 

Demo on 3v4l.org