PHP多个数组 - 使用对象回显数组键的值

PHP多个数组 - 使用对象回显数组键的值

问题描述:

<?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

那么,从这个代码来看,你有什么是一样的东西

 
$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,这将使更多的意义对我来说