-3

好的,所以第二次发布问题,我在第一个问题上取得了巨大的成功,所以我又来了。
我有一个数组,其中填充了 8 个其他数组,其中包含 5 个值,例如 0,2,5,0,1(值也不固定)。我需要做的是将一个数组 (1,2,3,4,5) 乘以我存储在第一个数组中的 8 个数组中的每一个。
这就是我所拥有的,代码从我拥有的按钮中获取值并将它们存储在数组中:

$filename = "Results.txt";
$lines = file($filename);

$q1 = $_POST['q1']; //stored value between 1-5
$q2 = $_POST['q2'];
$q3 = $_POST['q3'];
$q4 = $_POST['q4'];
$q5 = $_POST['q5'];
$q6 = $_POST['q6'];
$q7 = $_POST['q7'];
$q8 = $_POST['q8'];

$qN = 1;  //question number
$newLines = '';
$values = array("1", "2", "3", "4", "5");
$total = array();
    foreach($lines as $line) {

        $line = trim($line);  //remove excess newlines etc.
        $lineArr = explode(',',$line);  //split line into array by commas
        $index = ${'q'.$qN}-1; //zero based

    if (isset($lineArr[$index])){
        $lineArr[$index]++;  //add to position by one vote.
        $total = array_sum($lineArr);
    $newLines .= implode(',',$lineArr) . "\r\n";
    $qN++;
}

//write contents back to file.<br/>
file_put_contents($filename, $newLines);



所以这就是我所拥有的,我希望应该很清楚,但是是的,我需要取计算值,然后将它们除以第一个数组中每一行的总和。我希望这解释得足够清楚,我也意识到如果将这些值加载到数据库中会好得多,不幸的是这不是我需要的。谢谢!

4

1 回答 1

0

如果我理解正确,您需要使用以下 2 个数组 -

$q1 = array(0,1,2,2,4);
$values = array(1,2,3,4,5);

并将它们相乘 -

$q1 * $values

要得到 -

$result1 = array(0,2,6,8,20);

去做这个 -

首先,改变你的$q#变量 -

$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
...
$q7 = $_POST['q7'];
$q8 = $_POST['q8'];

到一个数组 -

$q[1] = $_POST['q1'];
$q[2] = $_POST['q2'];
...
$q[7] = $_POST['q7'];
$q[8] = $_POST['q8'];

然后使用嵌套for循环 -

$result = array();  // Creates a Results array
for($i=0;$i<count($q);$i++){   //loops through number of questions. '$i<count($q)' makes it so you can do less (ie. 'q[5]') or more (ie. 'q[14]') without having to change the for loop
    for($j=0;$j<count($values);$j++){   //loops through number of values in your $values array. '$i<count($values)' makes it so you can do less (ie. 'array(1,2,3)') or more  (ie. 'array(1,2,3,4,5,6)') without having to change the for loop
          $result[$i+1][$j] = $q[$i+1][$j]*$values[$j];}  // create array $result[1] = array(#,#,#,#,#), etc.
}

您可以查看这个 PHPFiddle 作为示例。http://phpfiddle.org/main/code/45a-6j0

这会给你这样的结果 -

$q[1] = array(4,5,2,0,5)
$q[2] = array(5,1,0,0,1)
$q[3] = array(1,4,2,0,0)
$q[4] = array(4,5,0,0,4)
$q[5] = array(2,2,3,4,0)
$q[6] = array(5,4,3,2,0)
$q[7] = array(2,1,5,4,2)
$q[8] = array(4,4,3,5,5)

Results
$result[1] => array(4,10,6,0,25)
$result[2] => array(5,2,0,0,5)
$result[3] => array(1,8,6,0,0)
$result[4] => array(4,10,0,0,20)
$result[5] => array(2,4,9,16,0)
$result[6] => array(5,8,9,8,0)
$result[7] => array(2,2,15,16,10)
$result[8] => array(4,8,9,20,25)
于 2012-12-12T22:51:00.207 回答