php使用嵌套for循环外的变量

时间:2014-03-21 21:28:15

标签: php mysql

嗨,这可能是一个新问题,但我无法让我的代码工作。 我试图将数据库中单元格中给出的数字相加。然后通过计算总和值的数组来轻松访问它们。

让事情变得更加清晰。该数据库包含许多行,这些行将通过相同类型的代码。每行至少有40个单元格(我只挑选单元格13-33)。 单元格包含12个数字,每个数字为“011011100005”。我不想把所有细胞加在一起。 只需将每个单元格中的nubers相加。

<?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。

1 个答案:

答案 0 :(得分:0)

基本上,如果您希望变量在循环外可见,则必须在循环外创建变量。所以在开始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);