PHP 数组项全部命名为零


php array items all named zero

我有一个数据表,其中高度在不同的行中,例如 600,700,800。 如果用户在表单中输入 650,则查询需要选择高度参数为 700 的行(它始终转到较大的项目。 我的问题是我已经选择了高度项目并且它在一个数组中,但是我如何给每个数组行一个新名称,例如rowitem1,rowitem2,rowitem3,以便我以后可以执行查询? 数组中的所有项目都是 ['0']。 我需要每行递增。

$res2 = mysqli_query($con,"SELECT height FROM datatable WHERE blind = '$blindselected2'");
while($row2 = mysqli_fetch_array($res2)) {
$rowitem = $row2['0'];
if ($height2 == $rowitem) {
    $selectedrowitem = $rowitem;
}
if ($height2 > $rowitem && $height2 < $nextrowitem) {
    $selectedrowitem = ....
}

编辑:打印数组的输出

    Array ( [0] => 0 [height] => 0 ) 
Array ( [0] => 600 [height] => 600 ) 
Array ( [0] => 700 [height] => 700 ) 
Array ( [0] => 800 [height] => 800 ) 
Array ( [0] => 900 [height] => 900 ) 
Array ( [0] => 1000 [height] => 1000 ) 
Array ( [0] => 1100 [height] => 1100 ) 
Array ( [0] => 1200 [height] => 1200 ) 
Array ( [0] => 1300 [height] => 1300 ) 
Array ( [0] => 1400 [height] => 1400 ) 
Array ( [0] => 1500 [height] => 1500 ) 
Array ( [0] => 1600 [height] => 1600 ) 
Array ( [0] => 1700 [height] => 1700 ) 
Array ( [0] => 1800 [height] => 1800 ) 
Array ( [0] => 1900 [height] => 1900 ) 
Array ( [0] => 2000 [height] => 2000 )

我还尝试了以下方法:

while($row2 = mysqli_fetch_array($res2)) {
$rowitem = $row2['height'];
echo current($row2) .  next($row2);
echo '<br>';
if ($height2 == current($row2['height'])) {
    $selectedrowitem = $rowitem;
} elseif ($height2 > current($row2) && $height2 < next($row2)) {
    $selectedrowitem = next($row2);
    break;
} else {
    $selectedrowitem = 'error';
}
}//WHILE

和回波电流的输出($row 2)。 下一页($row 2);如下,我可以看到它没有转到下一项:

*

00
600600
700700
800800
900900
10001000
11001100
12001200
13001300
14001400
15001500
16001600
17001700
18001800
19001900
20002000

*

当您使用 currentnext 指令时,您不会循环访问行,而是循环访问行内的索引。

当你做$row2 = mysqli_fetch_array($res2)你没有关于前一行或下一行的信息(没有额外的复杂的身体运动和敲打手鼓)。如果要获得此类信息,则需要使用 mysqli_fetch_all 从数据库中获取完整结果,并使用foreachfor循环迭代此结果。

如果要选择一些大于或等于用户在表单中提到的高度,则需要修改查询以仅选择较大或相等的行。

$res2 = mysqli_prepare(
    $con,
    'SELECT `height` FROM `datatable` WHERE `blind` = ? AND `height` >= ?'
);
$res2->bind_param('si', $blindselected2, $height2);
$res2->execute();
$res2 = $res2->get_result();
while ($row2 = $res2->fetch_assoc()) {
    echo $row2['height'] . '<br>';
}

就这样。您可以修改 SQL 查询,以避免代码中溢出无助于简化算法的指令。

将代码更改为以下代码

$res2 = mysqli_query($con,"SELECT height FROM datatable WHERE blind = '$blindselected2'");
while($row2 = mysqli_fetch_array($res2)) {
$rowitem = $row2['height']; //you should change this row.
if ($height2 == $rowitem) {
    $selectedrowitem = $rowitem;
}
if ($height2 > $rowitem && $height2 < $nextrowitem) {
    $selectedrowitem = ....
}

希望它能帮助你。只需将 0 更改为"高度"