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

时间:2011-02-01 10:07:56

标签: php sql arrays oop

<?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-&gt;名称时;什么都不会出现。如何添加此代码以使用$newObject->name;显示数据 提前谢谢。

1 个答案:

答案 0 :(得分: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,这对我来说更有意义