PHP返回三倍的结果


PHP returning tripled results

所以我知道脚本在做什么,我想我理解为什么它会出现3次,但我不知道如何修复它!

这是目前的脚本:

$flagquery = "SELECT incident_flag FROM incident_attributes WHERE incident=2157"; 
$flagresult = mysqli_query($conn, $flagquery);
if (mysqli_num_rows($flagresult) > 0) {
while($firow = mysqli_fetch_array($flagresult)){ 
    foreach ($items as $flagrow) {
    $id = $flagrow['id'];
    $name = htmlspecialchars($flagrow['name'], ENT_QUOTES);
    $form .= " <div class='form-group'>
                    <label class='col-sm-2 control-label'>$name</label>
                    <div id='name-input-wrapper' class='col-sm-8 controls'>
                    <input type='checkbox' value='$id' name='flags[]' ";
    if ($firow["incident_flag"] == $id) $form .= 'checked';
    $form .= ">
                    </div>
                </div>";
    }
 }
}
echo $form;

这是相关的阵列

Array
(
[1] ( Array
    (
        [id] => 1
        [name] => Bag
        [flag] => 0
    )
[2] => Array
    (
        [id] => 2
        [name] => Screen
        [flag] => 0
    )
[3] => Array
    (
        [id] => 3
        [name] => HD
        [flag] => 0
    )
)

这是mysql数据库incident_attributes

id incident incident_flag
1   2157    1
2   2157    2
3   2157    3

脚本的全部目标是标记选中的复选框。还有其他方法吗?

您为每个结果的行(3)回显3个复选框,因此您有9个复选框而不是3个。您必须反转两个foreach,并将嵌套的foreach的求值限制为checked

由于查询结果变成了嵌套的foreach,所以在执行循环之前必须提取行:

$firows = mysqli_fetch_all( $flagresult, MYSQLI_ASSOC );
foreach( $items as $flagrow ) 
{
    $id    = $flagrow['id'];
    $name  = htmlspecialchars( $flagrow['name'], ENT_QUOTES );
    $form .= " <div class='form-group'>
                    <label class='col-sm-2 control-label'>$name</label>
                    <div id='name-input-wrapper' class='col-sm-8 controls'>
                    <input type='checkbox' value='$id' name='flags[]' ";
    foreach( $firows as $firow )
    {
        if( $firow["incident_flag"] == $id ) $form .= 'checked';
    }
    $form .= ">
                    </div>
                </div>";
}

作为替代方案(无嵌套foreach):

$firows = mysqli_fetch_all( $flagresult, MYSQLI_ASSOC );
$flags  = array_column( $firows, 'incident_flag' ); // $flags now is [ 1,2,3 ]
foreach( $items as $flagrow ) 
{
    (...)
    $form .= " <div class='form-group'> ... "
    if( in_array( $id, $flags ) ) $form .= 'checked';
    (...)
}