从数据库表打印格式化的多维数组

时间:2013-12-03 21:43:19

标签: php mysql arrays

我有一个包含两个字段的数据库表,subject_id和teacher_id。在subject_id字段中是代表数学,科学,英语等科目的数字。 teacher_id字段代表各种教师。他们在同一行上的存在意味着教师1教授科目2,或者在不同的行上,教师1教授科目5,或者在不同的行上教师4教授科目2等...这是多对多的关系。

从数据库查询后,我得到了一个这种结构的数组:

Array
(
[0] => Array
    (
        [first_name] => bob
        [subject_en_name] => italian
    )

[1] => Array
    (
        [first_name] => bob
        [subject_en_name] => japanese
    )

[2] => Array
    (
        [first_name] => bob
        [subject_en_name] => korean
    )

[3] => Array
    (
        [first_name] => sally
        [subject_en_name] => math
    )

[4] => Array
    (
        [first_name] => sally
        [subject_en_name] => GMAT
    )

我需要屏幕显示名字,并打印出如下句子:

Bob teaches italian, japanese, korean...
Sally teaches math, GMAT...

使用foreach构造

foreach ($teacher_object as $t_object)
{
    echo $t_object['first_name'] . " teaches " . $t_object['subject_en_name'] . "<br>";

}

我只能管理这些打印输出:

bob teaches italian
bob teaches japanese
bob teaches korean
sally teaches math
sally teaches GMAT

是否有用于排序数组的php函数可以帮助我?其他一些解决方案?

1 个答案:

答案 0 :(得分:4)

首先重新排列数组,以便有一个新的数组,其中教师名称作为索引,类作为子数组:

$teaches = array();
foreach ($teacher_object as $t_object) {
    $teaches[$t_object['first_name']][] = $t_object['subject_en_name'];
}

新数组将如下所示:

Array
(
    [bob] => Array
        (
            [0] => italian
            [1] => japanese
            [2] => korean
        )

    [sally] => Array
        (
            [0] => math
            [1] => GMAT
        )

)

现在你有一个更容易循环的数组。像这样:

foreach($teaches AS $teacher => $classes) {
    echo $teacher . " teaches " . implode(", ",$classes) . "<br/>";
}

给你......

bob teaches italian, japanese, korean
sally teaches math, GMAT