2017-10-14 68 views
-1

我需要通过添加两个交替数字来创建一个数字数组,我不知道如何去做。通过添加两个交替数字创建一个数字数组

我需要添加4,然后8交替,直到我有大约200个总数的项目在数组中。起始号码不应包括在内。以使阵列应该是:

[4,12,16,24,28,36,40,48 ...]

什么是完成在PHP的最佳方式?

+0

*“最佳方式”*是主观的。我确定有很多方法,其中一个是for()'循环,并且在那里增加了一些内容?我会尝试一下,看看它是否有效。 – Rasclatt

回答

0

有几个方法可以做到这一点...

这仅仅是一种方式......

<?php   
$sequence_array = array(); 
$sequence_array[0] = 4;  // Seed the initial entry 
for ($i = 1; $i < 200; $i++) { 
    $step = ($i % 2) ? 8 : 4; // Decide whether to add a 4 or an 8 
    $sequence_array[$i] = $sequence_array[$i - 1] + $step; 
} 
var_dump($sequence_array); // Lets peek at the result 

所以基本上种子与起始号码4

第一入口在索引上执行一个模2,就像奇数/偶数的事物一样,这给了我们“交替”效应。

根据位置是“奇数/偶数”,$步计算为4或8。

您可以为交替数字设置更多的功能和设置/使用变量。但我把它留给你,如果你需要它:)

好吧,我不能让它成为...

所以,你可以这样定义一个函数...

function build_alternating_array($first_value, $second_value, $total_entry_count) { 
    $array = array(); 
    $array[0] = $first_value; // Seed the initial value 
    for ($i = 1; $i < $total_entry_count; $i++) { 
     $step = ($i % 2) ? $second_value : $first_value; 
     $array[$i] = $array[$i - 1] + $step; 
    } 

    return $array; 
} 

,并调用它像这样...

$sequence_array = build_alternating_array(4, 8, 200); 
var_dump($sequence_array); // Lets peek at the result 
0

只是一个简化版本:

$b = []; 
$d = 0; 
for($a =0; $a<=200; $a++) 
{ 
    $d += $a % 2 ? 8 : 4; 
    array_push($b , $d); 
} 

print_r($b); 
+0

这是比我想出的更好的解决方案:) – TimBrownlaw