矩阵包含意外的空值



>我正在尝试创建一个多维数组,其中包含每行数据中每列的每个值。首先,我创建一个空的全局数组来存储值。然后我使用 looping with 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] => )

你对$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;

最新更新