开发者

PHP referring to object data with numerical key

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 t开发者_运维百科o 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.


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.


echo $myobject->data[$counter];

If I'm not mistaken.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜