2012-11-26 125 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