PHP:使用foreach在多维数组中显示特定数据

时间:2012-11-26 09:38:04

标签: php mysql

我有一个包含从mysql表中查询的数据的数组,我想使用foreach在数组中显示特定数据(特定列数据)。

+------+-------+------+-----+
| id   | name  | sex  | age |
+------+-------+------+-----+
|    1 | tom   | m    |  18 |
|    2 | jane  | f    |  32 |
|    4 | Doyle | m    |  25 |
+------+-------+------+-----+

假设数组名称是$ candidate,我需要从$ candidate中显示的只是colum'name'中的名称....

我完全使用while循环完成了这项工作,但我不想再次运行数据库查询,因为数据已经存在于数组$ candidate

以下是代码:

1. Class function performing the query

       <?php

    class pubCourses {
            function getPubRegCand($org_id, $c_id){
            //fetch the list of registered candidates for this course
            $query_reg_cand = @mysql_query("select * from public_reg_cand where org_id='".$org_id."'");
            $cand = array();
            $cand = @mysql_fetch_assoc($query_reg_cand);

            return $cand;
                    }
          }
        ?>

2. Calling the class function 

    <?php
        $obj = new pubCourses();
        $candidates = array();
        if(isset($_GET['c_id']) && isset($_GET['org_id'])){
            $candidates = $obj->getPubRegCand($_GET['org_id'], $_GET['c_id']);
        }
    ?>

3. Foreach statement to display the candidates names


      <?php

        foreach($candidates as $id=>$cands){
      ?>
     <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td class="bold">Participant&#039;s Name: <?php echo ucwords($cands['name']); ?></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
     </tr>
     <?php
        }
     ?>

上面的foreach声明没有显示我需要的'名字',而是显示第一行的第一个字符,即1,t,m,1 ......

请帮助我...谢谢

2 个答案:

答案 0 :(得分:1)

为什么不对您的查询进行常规while循环?

$mysqli = new mysqli("localhost", "user", "password", "db_name");
$query = "SELECT name FROM your_table";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        echo <<<HTML 
<tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="bold">Participant&#039;s Name: {$row['name']}</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
HTML;
        //echo $row['name'];
    }
}

答案 1 :(得分:0)

因为你要从db ...

返回一行

使用

 while($row=mysql_fetch_array($query_reg_cand)) {
   $cand[] = $row;
 }

而不是

$cand = @mysql_fetch_assoc($query_reg_cand);

这应该做....不需要使用$id=>$cands(除非你想要密钥)。你可以做..

 foreach($candidates as $cands){...

最后

Use of mysql extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used