首页 > 解决方案 > php 内爆函数空数组不起作用

问题描述

我正在尝试从查询中获取数组中的值,并通过使用 implode 将数组值转换为字符串,直到它工作正常,

因此,在那之后,我在选择框中的另一个 where 条件查询中传递了该内爆变量,所以现在发生的情况是,如果数组为空,则选择框正在消失,谁能帮我解决这个问题..

这是我的代码

<select name="course1id" class="form-control" required> 
                            <?php
                            $r = array();
                            $query = "SELECT course1id,course2id FROM mdl_course_relation";
                            $result = $DB->get_records_sql($query);
                            foreach ($result as $res) {

                                $r[] = $res->course1id;
                                $r[] = $res->course2id;

                            }


                            $courseids = implode(",", $r);
                            //$where = '';

                            //if (sizeof($r))

                                //$where .= 'AND id NOT IN($courseids)';

                            ?> 


                            <?php
                            $sql = "select id,fullname from {course} WHERE id!=1 AND id NOT IN($courseids)";


                            $courses = $DB->get_records_sql($sql);
                            ?> 

                            <option value="">Choose Course</option> 
                            <?php
                            if (sizeof($courses)): foreach ($courses as $row):
                                    $coursename = $row->fullname;
                                    ?> 
                                    <option value="<?php echo $row->id . '|' . $row->fullname; ?>"><?php echo $row->fullname; ?></option> 
                                    <?php
                                endforeach;
                            endif;

                            ?> 
                        </select>

标签: phpmysql

解决方案


您需要检查空数组

像这样更新代码

$courseids = implode(",", $r);
$where = '';

if (count($r)>0)
{
    $where = "AND id NOT IN($courseids)";
}
$sql = "select id,fullname from {course} WHERE id!=1 $where";
$courses = $DB->get_records_sql($sql);

推荐阅读