如何在PHP语言中使用数组

时间:2016-04-26 20:18:05

标签: php

我有这段代码,但是当我运行它时它会给我错误(注意:未定义的偏移:在$str[$row['term_no']] += ",".$row['code'];的C:\ wamp \ www \ test3.php中为1)

我该如何解决这个问题?

<?php

$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, "uoh");
$q = " SELECT * FROM `degree_plan` LEFT JOIN courses ON
    degree_plan.course_number=courses.course_number
    where major='COE'";

$result = mysqli_query($con, $q);
if ($result) {

    $str = [];
    while ($row = mysqli_fetch_array($result)) {
        {
            $str[$row['term_no']] += "," . $row['code'];
        }
        foreach ($str as $key => $value) {

            echo $value;
            echo $key;
        }

    }
}

?>

2 个答案:

答案 0 :(得分:0)

在您的代码中,您将所有代码放在一个从未定义过的元素中。

改变这个:

$str[$row['term_no']] += ",".$row['code'];

到此:

$str[$row['term_no']] = $row['code'];

答案 1 :(得分:0)

发生错误是因为数组元素不存在,因此,首先检查元素:如果存在,添加,如果它不存在,则创建:

while($row = mysqli_fetch_array($result))
{
   if ( isset( $str[$row['term_no']] ) ) // IF ELEMENT EXISTS...
        $str[$row['term_no']] .= ",".$row['code']; // ADD TO ELEMENT.
   else $str[$row['term_no']] =  $row['code'];  // CREATE ELEMENT.
}