2

I am constructing an array like this:

$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');
}

This gives me a fatal exception "Cannot access empty property"

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

but this works

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

Is there a better way to get the "total amount" from this object?

Even better - how can I make it so the object performs like this

 echo $list->$index->total_amount
4

1 回答 1

1

Ah, i see the problem.

The way you are using it now you're trying to access the element 'total_amount' of array index, not the element total_amount` of the array $list->$index. And of course,as $index is only an array key and as such a string or int, it won't work.

What about this: <td><?=$list->{$index}['total_amount']?></td>

About your last question (accessing values via $list->$index->total_amount): You could probably cast your array to an object with (object).

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

------- Original Answer -------

I don't know your exact object, but try the following:

$transaction_list->index['total_amount']

Notice the missing $ in front of the index? That's the actual way to access class member variables. When using $ you're actually doing something else.

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

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

于 2012-09-07T11:38:04.923 回答