这是一个假设性的问题。如果我有3个数组来自3个单独的sql db查询,它们都与另一个相关。例如。。。

//db
schools
id | school_name

classes
id | class_name | school_id

students
id | student_name | class_id

我想把所有的东西都列成这样。。。
//php
foreach(schools as school){

    echo '<h1>' . $school->school_name . '<h1>';

    foreach(classes as class){

        if($class->school_id == $school->id){

            echo '<h2>' . $class->class_name . '<h2>';

            foreach(students as student){

                if($student->class_id == $class->id){

                    echo '<h3>' . $student->student_name . '<h3>';

                }
            }
        }
    }
}

我要打3个数据库电话。有没有办法在一个数据库查询中获取所有这些信息?就像一个数组中的一个数组,然后以某种方式循环?或者这是最好的方法吗?

最佳答案

<?php

try {
    $pdo = new PDO("mysql:host=127.0.0.1;dbname=school", "username");
} catch (PDOException $e) {
    echo "PDO Connection failed: " . $e->getMessage();
    exit(1);
}

$sql = <<<SQL

    SELECT schools.school_name, classes.class_name, students.student_name
    FROM
        schools INNER JOIN classes ON (schools.id = classes.school_id)
        INNER JOIN students ON (classes.id = students.class_id)
    ORDER BY 1, 2;

SQL;

$result = $pdo->query($sql);
if ($result == false) {
    die("query failed?!");
}

$school = "";
$class = "";
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    if ($school != $row['school_name']) {
        $school = $row['school_name'];
        echo "\nSchool:  $school\n\n";
    }
    if ($class != $row['class_name']) {
        $class = $row['class_name'];
        echo "   Class:  $class\n\n";
        echo "      Student list:\n";
    }
    echo "         {$row['student_name']}\n";
}

关于php - PHP foreach在foreach在foreach,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17494782/

10-13 08:13