2011-02-01 48 views
1
<?php 

/* SC: Shop Category */ 
$SCStatement = "SELECT * FROM shop_categories"; 
$SCQuery = mysql_query($SCStatement); 

while($SCFetch = mysql_fetch_array($SCQuery)){ 
    $SCItems[] = array(
     'id' => $SCFetch['id'], 
     'name' => $SCFetch['cat_name'], 
     'desc' => $SCFetch['cat_description'] 
    ); 
} 

$SCNumCols = 2; 
$SCNumItems = count($SCItems); 
$SCNumRows = ceil($SCNumItems/$SCNumCols); 



function bindArrayToObject($array) { 
    $return = new stdClass(); 
    foreach ($array as $k => $v) { 
     if (is_array($v)) { 
      $return->$k = bindArrayToObject($v); 
     } 
     else { 
      $return->$k = preg_replace ('/<[^>]*>/', '', $v); 
     } 
    } 

    return $return; 
} 

$newObject = bindArrayToObject($SCItems); 

echo $newObject->name; 

?> 

從數據庫中檢索到的數據存儲在$ SCItems []數組中。問題是,當我回聲$ newObject-> name;什麼都不會出現。如何添加此代碼以顯示使用的數據$newObject->name; 在此先感謝。PHP多個數組 - 使用對象回顯數組鍵的值

+1

什麼是你想達到什麼目的?您將在結果中將多個行綁定到對象,您將只獲取最後一行。你需要一些對象。有很多邏輯錯誤 – 2011-02-01 10:13:32

+0

僅供參考,從數據庫中提取數據時,如果要將列重命名爲其他內容,可以直接查詢,例如:SELECT id,cat_name as name,cat_description as desc FROM shop_categories` – naiquevin 2011-02-01 10:19:11

回答

0

那麼,從這個代碼來看,你有什麼是一樣的東西

 
$SCItems = Array(
0 => Array(
    'id' => 1, 
    'name' => 'name 1', 
    'desc' => 'description 1' 
), 
1 => Array(
    'id' => 2, 
    'name' => 'name 2', 
    'desc' => 'description 2' 
), 
); 

,然後從你的bindArrayToObject函數試圖建立對象

 
$newObject = new stdClass(); 
$newbject->0 = new stdClass(); 
$newbject->0->id = 1; 
$newbject->0->name = 'name 1'; 
$newbject->0->desc = 'description 1'; 

$newbject->1 = new stdClass(); 
$newbject->1->id = 2; 
$newbject->1->name = 'name 2'; 
$newbject->1->desc = 'description 2'; 

所以,你應該怎麼做循環顯示您的'$ SCItems',然後在每個條目上使用bindArrayToObject

例如

 
$SCObject = Array(); 
foreach($SCItems as $SCItem) { 
$SCObjects[] = bindArrayToObject($SCItem); 
} 

從那裏,你應該能夠訪問$SCObjects[0]->name,這將使更多的意義對我來說