从Foreach Php删除重复项

时间:2018-07-20 06:05:19

标签: php

这是我的目标,尝试删除重复项,并保持爆炸值和所选的$ classQuery语句匹配

enter image description here

$examQuery = $examClass->get_examByID($id);

$examRow = $examQuery->fetch_assoc();

$classes = explode(',', $examRow['class_id']);

$classQuery2 = $con->query("SELECT * FROM `class` WHERE `school_id` = '{$examRow['school_id']}' ");
if ($classQuery2->num_rows < 1):
    $output .= '';
else:

    while ($class_rows = $classQuery2->fetch_assoc()):
        foreach ($classes as $class):
            if ($class_rows['class_id'] === $class):
                $output .= '<option selected value="' . $class_rows['class_id'] . '">' . $class_rows['class_title'] . '</option>';
            else:
                $output .= '<option value="' . $class_rows['class_id'] . '">' . $class_rows['class_title'] . '</option>';
            endif;
        endforeach;
    endwhile;
endif;

2 个答案:

答案 0 :(得分:1)

您应该能够简单地通过在查询中添加GROUP BY来解决此问题;

$classQuery2 = $con->query("SELECT * FROMWHERE school_id = '{$examRow['school_id']}' GROUP BY class_id");

否则,我可能会保留一个已经使用过的数组,并在回显之前检查键是否在其中;

例如;

// the array of items to loop over (which has a duplicate in it)
$myArray = ['english', 'maths', 'science', 'geography', 'english'];

// an array to place the item name when it's been used once
$alreadyUsed = [];

foreach($myArray as $item) {
    // if the item doesn't already exist in $alreadyUsed then 
    // echo it out and add it to the array.
    if (! in_array($item, $alreadyUsed)) {
        echo $item . "<br>";
        $alreadyUsed[] = $item;
    }
}

答案 1 :(得分:0)

您正在比较不同的类型!

如果要进行良好的比较,则需要比较相同类型的值
例如 Integer === Integer || String === String || Object === Object


在您的情况下,您必须将$ class_rows ['class_id']与您的课程 ID
像这样:

if ($class_rows['class_id'] === $class.id):
            # Successful Condition
else:
            # Unsuccesful Condition
endif;