dpd20130 2017-02-07 11:18
浏览 45
已采纳

PHP:检索外部函数时的数组到字符串转换

Good day!

I have a problem here that I can't solve (last 5hrs).

here's my codes:

include 'assets\functionetrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
    $loadGradProgram[$i] = getCourseInfo(); 
}
echo $loadGradProgram[0];

getCourseInfo function

Solution 1:

function getCourseInfo(){
    $getInfo = array();
    include 'assets\database\connect.php';
    $i = 0;
    $x = 0;
    $sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
    $sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $getInfo[$i] = $row;
            $i++;   
        }

        return $getInfo;
    }
}

Result: Array to string conversion

Solution 2:

function getCourseInfo(){
    $getInfo = array();
    $loadInfo = array();
    include 'assets\database\connect.php';
    $i = 0;
    $x = 0;
    $sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
    $sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $getInfo[$i] = $row;
            $i++;   
        }
        $conn->close();

        for($x,$x<=$i;$x++;){
            $loadInfo[] = implode(',', $getInfo[$x]);
        }

        return $loadInfo;
    }
}

Result: Still the same

and this line causing error: echo $loadGradProgram[0];

I use echo just to see if the query is working.

  • 写回答

1条回答 默认 最新

  • dongluan6784 2017-02-08 08:51
    关注

    if you want a multi-dimmentional array like in w3c documentation, you do it like this :

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $getInfo[$i][] = $row['courseID'];
            $getInfo[$i][] = $row['courseCode'];
            ...
            $i++;   
        }
    
        return $getInfo;
    

    then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :

    foreach($loadGradProgram as $key => $value) // here the key is useless
    {
        echo $value[0];
        echo $value[1];
    }
    

    or directly like this :

    echo $loadGradProgram[0][0];
    echo $loadGradProgram[0][1];
    echo $loadGradProgram[1][0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀