开发者

PHP Print keys from an object?

I have an object BIRD and then there is [0] through [10] and each number has a subheading like "bug" or "beetle" or "gnat" and a value for each of those.

I want to print

BIRD 
    [0]
       bug = > value 

I can't find out how to do this anywhere - there is talk of PUBLIC and PRIVATE and CLASS and that's 开发者_如何学运维where I fall off


You could easily do it by type casting the object:

$keys = array_keys((array)$BIRD);


Similar to brenjt's response, this uses PHP's get_object_vars instead of type casting the object.

$array = get_object_vars($object);
$properties = array_keys($array);


If the 'object' is actually an associative array rather than a true object then array_keys() will give you what you need without warnings or errors.

On the other hand, if your object is a true object, then you will get a warning if you try use array_keys() directly.

You can extract the key-value pairs from an object as an associative array with get_object_vars(), you can then get the keys from this with array_keys():

$keysFromObject = array_keys(get_object_vars($anObject));


Looks like array_keys might have stopped working on objects but, amazingly, the foreach construct works, at least on a php stdClass object.

$object = new stdClass();
$object->a = 20;
$object->b = "hello";
$keys = array_keys($object);
// array_keys returns null. PHP Version 7.3.3 windows
foreach($object as $key=>$value)
{
     // but this works
     echo("key:" . $key . " value:" . $value . "\n");
}


I could be wrong but try to use array_keys using a object as parameter. I believe that is possible in php. http://php.net/manual/en/function.array-keys.php

Anyway, read about reflection.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜