[英]How to iterate over an array of arrays
我希望有人可以提供幫助。
我確定它只是一個簡單的,我出於某種原因無法解決。
基本上我有一個類來處理我的所有數據庫函數(連接,選擇,插入,更新)。
在select函數中,我返回一個數組。
public function getAll($table, $cols, $where, $limit, $order) {
// Set the query variables
if($cols == '') {
$cols = '*';
}
if($where!='') {
$where = ' WHERE '.$where;
}
if($limit!= '') {
$limit = ' LIMIT '.$limit;
}
if($order!='') {
$order = ' ORDER BY '.$order;
}
// Make the query string
$sql = 'SELECT '.$cols.' FROM '.$table.$where.$order.$limit;
//echo $sql;
// Set the query
$news_qry = mysql_query($sql);
// Set the array
$rows = array();
// Run a loop through the results
while($item = mysql_fetch_object($news_qry))
{
// Add each row to an array.
$rows[] = $item;
}
return $rows;
}
這個功能正常,因為我可以打印一個數組。 見下文:
Array ( [Gallery_id] => 1 [Gallery_Name] => Test [Gallery_FolderName] => Test Folder )
但是當我去使用這個對象時 -
$arr_GalleryInfo = $dataObj->getAll('tbl_Gallery', '', '', '', '');
在每個循環中(見下文)我只從數據庫中得到結果的第一個字母。
<?php
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
?>
<tr>
<td>
<?php echo $arrGallery['Gallery_Name']; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
</tr>
<?php
}
?>
任何幫助都會很棒。
謝謝。
更換:
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
etc...
有:
foreach ($arr_GalleryInfo as $arrGallery)
{
etc...
好吧,你的大問題是你正在嘗試迭代數組的0索引。
foreach ($arr_GalleryInfo[0] as $arrGallery) // get rid of the `[0]`.
這將使你真正得到一些合法的迭代,但還有一些其他的東西,你即將被擊中。
// this will output `Array`. You want $artGallery['Gallery_FolderName']
// or $artGallery['Gallery_id']
echo $arrGallery;
當然,您可以通過嵌套循環避免整個第二個問題:
foreach ($arr_GalleryInfo as $arrGallery) {
echo '<tr>';
foreach($arrGallery as $val ) echo "<td>$val</td>";
echo '</tr>';
}
如果$news_qry = mysql_query($sql);
失敗了,如果出現問題,你沒有什么可以警告你的。 你應該這樣做: $news_qry = mysql_query($sql) or die(mysql_error());
當然,您應該在所有數據庫輸入上使用mysql_real_escape_string
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.