如何在php中使用loop for()来保存数组$ n中的元素

时间:2014-09-04 10:43:14

标签: php arrays loops for-loop

请帮我用PHP解决这个等式。我有以下变量:

$p = 5;
$n = array();
$y = array(4,2,7,10,5,16,77,28,19,65,8,21);
$s1 = 10;
$h = array();

我的公式如下:

n1 = p*s1*y1; h1 = s1;
n2 = p*s1*y2; h2 = s1;
n3 = p*s1*y3; h3 = s1;
n4 = p*s1*y4; h4 = s1;
n5 = p*s1*y5; h5 = s1;
n6 = p*s1*y6; h6 = s1;

s2 = s1+n1+n2+n3+n4+n5+n6;
n7 =  p*s2*y7; h7 = s2;
n8 =  p*s2*y8; h8 = s3;
n9 =  p*s2*y9; h9 = s4;
n10 =  p*s2*y10; h10 = s5;
n11 =  p*s2*y11; h11 = s6;
n12 =  p*s2*y12; h12 = s7;

s3 = s2+n7+n8+n9+n10+n11+n12;

....

如何使用$n循环将数据保存在数组for()中?

1 个答案:

答案 0 :(得分:0)

这是:

$p = 5;
$n = array();
$y = array(4,2,7,10,5,16,77,28,19,65,8,21);
$s = array( 1 => 10);
$k = 1;

for($i = 1; $i <= count($y); $i++)
{
    $n[$i] = $p * $s[$k] * $y[$i-1];

    if($i % 6 === 0) {
        $k++;
        $s[$k] = $n[$i] + $n[$i-1] + $n[$i-2] + $n[$i-3] + $n[$i-4] + $n[$i-5];
    }
}

print_r($s);
print_r($n);

结果:

Array
(
    [1] => 10
    [2] => 2200
    [3] => 2398000
)
Array
(
    [1] => 200
    [2] => 100
    [3] => 350
    [4] => 500
    [5] => 250
    [6] => 800
    [7] => 847000
    [8] => 308000
    [9] => 209000
    [10] => 715000
    [11] => 88000
    [12] => 231000
)

Live preview