好的第二次发布问题,第一次我取得了很大成功,所以我再来一次。
我有一个数组填充了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);
所以这就是我所拥有的,我希望它应该非常清楚,但是我需要取计算值,然后将它们除以第一个数组中每一行的总和。我希望这个解释得足够清楚,我也意识到如果将值加载到数据库中会有多好,不幸的是,这不是我需要的。谢谢!
答案 0 :(得分: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#
vars -
$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)