无法访问空房产

时间:2012-09-07 11:33:31

标签: php arrays object

我正在构建一个这样的数组:

$result = $this->db->get($this->_table);
foreach ($result->result_array() as $row) 
{
    $list->$row['categories_id'] = array('total_amount' => $row['total_amount'], 'other_stuff' => 'stuff');
}

这给了我一个致命的例外“无法访问空房产”

<?foreach ($category_list as $index => $row) {?>
          <td><?=$row?></td>
          <td><?=$list->$index['total_amount']?></td>
   <?}?>

但这有效

<?foreach ($category_list as $index => $row) {?>
          <td><?=$row?></td>
          <? $temp = $list->$index; ?>
          <td><?=$temp['total_amount']?></td>
   <?}?>

有没有更好的方法从这个对象中获得“总金额”?

更好 - 我怎样才能使对象像这样执行

 echo $list->$index->total_amount

1 个答案:

答案 0 :(得分:1)

啊,我看到了问题。

您现在使用它的方式是尝试访问数组索引的元素'total_amount',而不是数组$ list-&gt; $ index的元素total_amount`。当然,因为$ index只是一个数组键而且是一个字符串或int,所以它不起作用。

这个怎么样:<td><?=$list->{$index}['total_amount']?></td>

关于您的上一个问题(通过$ list-&gt; $ index-&gt; total_amount访问值):您可以使用(object)将数组转换为对象。

$list->$row['categories_id'] = (object) array('total_amount' => $row['total_amount'], 'other_stuff' => 'stuff');

-------原始答案-------

我不知道你的确切对象,但请尝试以下方法:

$transaction_list->index['total_amount']

注意索引前面缺少的$?这是访问类成员变量的实际方法。使用$时,你实际上在做其他事情。

http://www.php.net/manual/en/language.oop5.basic.php

http://www.php.net/manual/en/language.variables.variable.php