我有一個數組包含從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> </td>
<td> </td>
<td class="bold">Participant's Name: <?php echo ucwords($cands['name']); ?></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<?php
}
?>
foreach語句上面沒有牛逼顯示的名字「我需要,而它的顯示第一行的第一個字符,即1,T,M,1 ...
請幫助我這個...謝謝
這似乎更像是一個數據問題?嘗試做'print_r($ candidates);'在你的foreach之上,看'name'字段是否包含全名? – Gavin
向我們展示你的查詢....看起來像從db中獲取數組時出現錯誤 – bipen
只需從參數中刪除'$ id =>'。所以它應該是'foreach($ candidate作爲$ cands){echo $ cands ['name'];}' – kpotehin