tags:

views:

193

answers:

4

I have converted an array to object data like this:

<?php
$myobject->data = (object)Array('zero','one','two);
print_r($myobject);
?>

And the output is:

stdClass Object ( [data] => stdClass Object ( [0] => zero [1] => one [2] => two ) )

So far so good. But if I try to refer to the numerical keys...

<?php
$myobject->data = (object)Array('zero','one','two);
$counter = 1;
echo $myobject->data->$counter;
?>

...nothing is returned! I would expect it to echo "one".

Am I doing it wrong?

+1  A: 

You could try accessing it as an array element. But I'm not sure whether that would work or not. However, what you can do is looping over the object elements (or rather, properties) using a foreach loop.

Like so:

foreach ($myobject->data as $key => $value)
    echo "$key is my key.<br />";

I'm just not sure whether you can access the key, too.

Franz
Did you test this? I'd be interested in knowing whether it works. Else, just use soulmerge's solution.
Franz
A: 
echo $myobject->data[$counter];

If I'm not mistaken.

Ben Dauphinee
Fatal error: Cannot use object of type stdClass as array
Al
As long as the class doesn't implement ArrayAccess, you can't access it this way: http://de2.php.net/manual/de/class.arrayaccess.php
Boldewyn
+3  A: 

That's an oddity in PHP, you need to access it using $object->data->{1}. Or you could convert it back to array for accessing the members. But I think it is best to have proper names for object members, try something like this, for example:

$myobject->data = (object)Array('m0' => 'zero','m1' => 'one','m2' => 'two');
$myObject->data->m1;
soulmerge
A: 

The problem you have is, that $counter is automatically converted to String for the look-up. Try

$myobject->$counter = "abc";
var_dump($myobject);

and you'll see what I mean. To circumvent this use the method Franz has proposed.

Boldewyn