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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With