矩阵包含意外的空值

时间:2019-12-10 12:03:35

标签: php arrays

我正在尝试创建一个多维数组,该数组包含每一行数据中每一列的每个值。首先,我创建一个空的全局数组来存储值。然后,我使用循环for将数据填充到数组中,然后打印该数组以确保它显示了应该存储的内容,但又以某种方式还存储了空值。这可能是因为我首先声明了一个空数组。我需要它仅包含表中具有n行和4列的值。连接是正确的,我已经检查过了,我认为它与循环或空数组变量有关。

//this is the code
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<?php
function proses_saw(){
    include 'koneksi.php';
    $matrix = array();
    $data = mysqli_query($koneksi,"SELECT * FROM konversi WHERE NIM");
    $rowcount = mysqli_num_rows($data);
    $culcount = mysqli_field_count($koneksi);
    $culcount = $culcount - 2;
    printf($rowcount);
    printf($culcount);
    echo "<br/>";
    for ($row = 0; $row < $rowcount; $row++) {
    for ($col = 0; $col < $culcount; $col++) {
        $d = mysqli_fetch_array($data);
        echo "<br/>";
        global $matrix;
        $matrix = array($d['ip'],$d['kt'],$d['prestasi'],$d['pb']);
        print_r($GLOBALS['matrix']);    
        }//end of for column
    }//end of for rows
} //end of function

?>
</body>
</html>
//this is what it shows
Array ( [0] => 5 [1] => 1 [2] => 1 [3] => 2 )
Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 2 )
Array ( [0] => [1] => [2] => [3] => )
Array ( [0] => [1] => [2] => [3] => )
Array ( [0] => [1] => [2] => [3] => )
Array ( [0] => [1] => [2] => [3] => )
Array ( [0] => [1] => [2] => [3] => )
Array ( [0] => [1] => [2] => [3] => )

1 个答案:

答案 0 :(得分:1)

您不需要在$col上进行内循环。对mysqli_fetch_array的每次调用一次获取整行,而不是一列。实际上,您应该只循环mysqli_fetch_array的状态;根本不需要使用$rowcount$colcount。另外,您已经声明了$matrix,因此无需再次声明。最后,当您可能想向数组中添加行时,每次循环都将覆盖$matrix中的值。试试这个:

while ($d = mysqli_fetch_array($data)) {
    echo "<br/>";
    print_r($d);    
    $matrix[] = array($d['ip'],$d['kt'],$d['prestasi'],$d['pb']);
} //end of while rows

此循环之后$matrix将包含(根据上面的输出)

Array (
    [0] => Array ( [0] => 5 [1] => 1 [2] => 1 [3] => 2 )
    [1] => Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 2 )
)

此时,您可能希望使用以下函数从函数中返回$matrix

return $matrix;