PHP返回三倍的结果

时间:2016-04-18 23:58:59

标签: php mysql arrays

所以我知道脚本在做什么,我想我明白为什么它会出现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 DB incident_attributes

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

脚本的整个目标是标记选中的框。还有其他方法吗?

1 个答案:

答案 0 :(得分:2)

您为每个结果的行(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';
    (...)
}