【问题标题】:simple loop that wraps around string not working?环绕字符串的简单循环不起作用?
【发布时间】:2021-02-08 05:44:29
【问题描述】:

基本上,我想生成任意长度的音符串,例如从 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 它不再工作了。为什么它只在循环内第一次起作用?

【问题讨论】:

    标签: php loops foreach logic


    【解决方案1】:

    您的问题是您试图在foreach 内的if 块中分配$number,但在每个循环结束时,$number 的值再次被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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多