嗨,这可能是一个新手问题,但我无法让我的代码工作。 我正在尝试对数据库中单元格中给出的数字进行求和。然后通过创建求和值数组来轻松访问它们。
让事情变得更清楚一些。数据库包含许多行,这些行将通过相同类型的代码。每行至少有 40 个单元格(我只挑选出 13-33 号单元格)。 这些单元格包含 12 个数字,每个数字为“011011100005”。我不想将所有单元格加在一起。 只需将每个单元格中的数字相加即可。
<?php
// Get row 1 from the database and put into variable $row1
$row1 = mysql_fetch_row($result);
// create an emty variable with the name $str, for use later outside of the for loop
$str = '';
// read in the cells with index 13 to 33.
for ($i = 13; $i < 33; ++$i) {
// put the values in a string and add "," between the values.
$str .= "$row1[$i],";
};
// Split the values into an array, useing "," as an divider.
$arr2 = ( explode( ',', $str ));
// Read in all the values from $arr2, index 0 to 20.
for ($p = 0; $p < 20; ++$p) {
// make variable $b2 to the values that are in $arr2[index 0 to 20].
$b2 = $arr2[$p];
$a2 = 0; // $a2 to 0
// for the first 10 numbers in the given strings $arr2[index 0 till 20].
for ($i = 0; $i < 10; ++$i) {
// sum those 10 numbers in every string
$a2 += $b2[$i];
};
// this is giving me the correct numbers like "909090900000000010230"
// 21 numbers that is the sum of every strings value.
print_r($a2);
};
这里开始我的问题,在循环之外使用 $a2 将不起作用。我该如何解决这个问题?
$arr1 = str_split($a2);
// Make an array of the string $a2, spliting every number. (not working)
echo $arr1[5]; // echo one number by the index. (not working)
?>
所以我的问题是需要能够在代码的许多地方回显 $arr1 。
最佳答案
基本上,如果您希望变量在循环外可见,则必须在循环外创建它。因此,在开始 for 循环之前对其进行初始化。
此外,数组比包含多个值的字符串更容易操作。因此,我做了一些更改以使处理更容易。
<?php
// Get row 1 from the database and put into variable $row1
$row1 = mysql_fetch_row($result);
// read in the cells with index 13 to 33.
$cells = array();
for ($i = 13; $i < 33; ++$i) {
// put the values in an array
$cells[] = $row1[$i];
};
// init cell total array
$cell_tot = array();
// Read in all the values from $arr2, index 0 to 20.
for ($p = 0; $p < 20; ++$p) {
// make variable $b2 to the values that are in $arr2[index 0 to 20].
$cell = $cells[$p];
// for the first 10 numbers in the given strings $arr2[index 0 till 20].
$cell_tot[$p] = 0;
for ($i = 0; $i < 10; ++$i) {
// sum those 10 numbers in every string
$cell_tot[$p] += $cell[$i];
};
// this is giving me the correct numbers like "909090900000000010230"
// 21 numbers that is the sum of every strings value.
echo $cell_tot[$p];
};
// cell_tot now visible outside the loop and is an array
// one occurance for each sumation process
// and contains one occurance for each sumation
// and not another string which is difficult to do anythig with
// also resolves the problem of one sumation adding up to more than a single char i.e. 1 to 9
// 10 would have caused you a problem
print_r($cell_tot);
关于php 在嵌套 for 循环之外使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569852/