2011-02-01 5 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을 echo했을 때입니다; 아무것도 나타나지 않습니다. 데이터를 표시하기 위해이 코드를 추가하려면 $newObject->name; 미리 감사드립니다.PHP 다중 배열 - 객체를 사용하여 배열 키의 값을 반향 출력합니다.

+1

당신은 무엇을 달성하려고? 당신은 하나 이상의 행을 객체에 바인딩하고 나중에 결과 만 얻을 수 있습니다. 당신은 객체 배열이 필요합니다. 많은 논리적 오류가 있습니다 –

+0

FYI, 데이터베이스에서 가져 오는 동안 다른 이름으로 열 이름을 바꾸려면 다음과 같이 직접 쿼리 할 수 ​​있습니다. - 'SELECT ID, 이름으로 cat_name, cat_description from desc FROM shop_categories' – naiquevin

답변

0

음,이 코드에서 판단, 당신이해야하는 것은 당신의 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 = Array(
0 => Array(
    'id' => 1, 
    'name' => 'name 1', 
    'desc' => 'description 1' 
), 
1 => Array(
    'id' => 2, 
    'name' => 'name 2', 
    'desc' => 'description 2' 
), 
); 

과 같은 '$ SCItems'을 루프 한 다음 각 항목을 사용하십시오. bindArrayToObject

나에게 훨씬 더 나을 당신이 $SCObjects[0]->name에 액세스 할 수 있어야합니다 거기에서
 
$SCObject = Array(); 
foreach($SCItems as $SCItem) { 
$SCObjects[] = bindArrayToObject($SCItem); 
} 

,

+0

대단히 감사합니다. 당신의 영웅 인 야콥 닐슨 - 엘레 (Jakob Nilsson-Ehle) – Kirk