什么是sql的正确方法,返回并格式化所有数组数据?

时间:2012-10-22 12:58:09

标签: php mysql sql arrays loops

我很感激这方面的一些帮助。 我已经实现了我想要的但我不知道这是否是最佳方式。

第一天我查询了数据库。

mysql_select_db($database);
    $sql_many_sections =" 
    SELECT sections.subject, sections.section_number, sections.classroom, 
    sections.level_id, sections.course, sections.campus, sections.times, 
    sections.shift
    FROM sections
    LEFT JOIN section_teacher 
    ON sections.section_number = section_teacher.section_number
    LEFT JOIN profile 
    ON profile.teacher_number = section_teacher.teacher_number
    WHERE profile_id ='{$colname_teacher}'
    ORDER BY sections.section_number ASC";

    // bring out the results as an array so I can loop through them later                   
    $result = mysql_query($sql_many_sections);
    confirm_query($result);
    while ($teaching_sections = mysql_fetch_array($result)) {
      $teaches[] = $teaching_sections;
    }

然后我print_r结果是。

Array
(
[0] => Array
    (
        [0] => English
        [subject] => English
        [1] => 32346
        [section_number] => 32346
        [2] => G635
        [classroom] => G635
        [3] => 2
        [level_id] => 2
        [4] => 236
        [course] => 236
        [5] => Male Science
        [campus] => Male Science
        [6] => 8 - 9:40 am, 10 - 11:40 am
        [times] => 8 - 9:40 am, 10 - 11:40 am
        [7] => AM
        [shift] => AM
    )

[1] => Array
    (
        [0] => English
        [subject] => English
        [1] => 49493
        [section_number] => 49493
        [2] => 1328
        [classroom] => 1328
        [3] => 2
        [level_id] => 2
        [4] => 236
        [course] => 236
        [5] => Male Humanities
        [campus] => Male Humanities
        [6] => 8 - 9:40 am, 10 - 11:40 am
        [times] => 8 - 9:40 am, 10 - 11:40 am
        [7] => AM
        [shift] => AM
    )

)

当我想现在返回这样的数据时

•   Section: 32346
•   Subject: English
•   Classroom: G635
•   Level: 2
•   Course: 236
•   Campus: Male Science
•   Shift: AM
•   Shift times: 8 - 9:40 am, 10 - 11:40 am

我能让它发挥作用的唯一方法就是做下面的事情,这是一个意外。 实现这些相同结果的正确方法是什么?感谢

<?php 
foreach($teaches as $value)
{ ?>
<ul>
<li>Section: <? echo  $value[1];?></li> 
<li>Subject: <? echo $value[0];?></li> 
<li>Classroom: <? echo $value[2];?></li> 
<li>Level: <? echo $value[3];?></li> 
<li>Course: <? echo $value[4];?></li> 
<li>Campus: <? echo $value[5];?></li> 
<li>Shift: <? echo $value[7];?></li> 
<li>Shift times: <? echo $value[6];?></li> 
</ul>
<?
} 
?>

1 个答案:

答案 0 :(得分:2)

你可以这样使用:

foreach ($teaches as $teach) {
    echo '<ul>';
    foreach ($teach as $name => $value) {
        $name = str_replace('_', ' ', $name);
        $name = ucfirst($name);
        echo '<li>' . $name . ': ' . $value . '</li>';
    }
    echo '</ul>';
}

显然我建议您使用mysql_fetch_assoc(),这样您只能获取数组键而不是索引。