PHP 返回三倍的结果

标签 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 数据库 event_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';
    (...)
}

关于PHP 返回三倍的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706253/

相关文章:

php - 如何从 while 循环中自动更改单选按钮的名称? PHP

mysql 将 1 个表连接到 2 个其他表

C#,如何通过分隔符拆分字节数组?

javascript - 我的 JSON 结果的输出

php - 如果 VAR 在 mySQL 数据库中,则返回该行数据作为变量 PHP

javascript - socket_bind()函数中的端口参数可以是80或443吗?

javascript - react : How to pass array of ids to method

php - 如何在 MySQL 中创建区分大小写的 'select' 和 'like'?

mysql - 从关系型数据库到Redis,N对N关系

javascript - 如何使用 AngularJS 填充复选框值列表?