【问题标题】:how to save elements in array $n by using loop for() in php如何在 php 中使用循环 for() 将元素保存在数组 $n 中
【发布时间】:2014-09-04 10:43:14
【问题描述】:

请帮助我在 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;

....

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

【问题讨论】:

  • 您能提供更多信息吗?

标签: php arrays loops for-loop


【解决方案1】:

这里是:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多