2012-11-26 61 views
0

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

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

假设数组名是$候选人,我需要从$显示考生是刚刚从科拉姆“名”的名字....

我已经这样做了完美的使用而循环,但我不希望再次运行数据库查询,因为数据在阵列$候选人

这里已经存在是代码:

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 ...

请帮助我这个...谢谢

+0

这似乎更像是一个数据问题?尝试做'print_r($ candidates);'在你的foreach之上,看'name'字段是否包含全名? – Gavin

+0

向我们展示你的查询....看起来像从db中获取数组时出现错误 – bipen

+1

只需从参数中删除'$ id =>'。所以它应该是'foreach($ candidate作为$ cands){echo $ cands ['name'];}' – kpotehin

回答

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']; 
    } 
} 
+0

感谢您的帮助...就像你建议的那样,我使用while循环以及它的工作正常,但我打算使用foreach由于某些原因... – Sms

+0

@ user1630911你去了,从我的经验 - 'while'是总是走的路。此外,如果您找到回答您的问题的答案,请接受它。这对你也很好。 –

+0

感谢您的帮助...既然foreach没有给我想要的东西,我只要坚持使用while循环就能正常工作......谢谢! – Sms

0

,因为你是从数据库返回行...

使用

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 
+0

感谢您的帮助...既然foreach没有给我想要的东西,我会坚持使用while循环,工作正常......谢谢! – Sms