PHP 从对象打印键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5803881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:32:38  来源:igfitidea点击:

PHP Print keys from an object?

phparraysobjectecho

提问by user723220

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.

我有一个对象 BIRD,然后有 [0] 到 [10],每个数字都有一个副标题,如“bug”或“甲虫”或“gnat”,以及每个数字的值。

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

我无法在任何地方找到如何做到这一点 - 有关于 PUBLIC、PRIVATE 和 CLASS 的讨论,这就是我失败的地方

采纳答案by Cloudson

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

我可能是错的,但尝试使用array_keys对象作为参数。我相信这在 php 中是可能的。 http://php.net/manual/en/function.array-keys.php

Anyway, read about reflection.

无论如何,请阅读反射。

回答by brenjt

You could easily do it by type casting the object:

您可以通过对对象进行类型转换来轻松完成:

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

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

回答by nick

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

与 brenjt 的响应类似,它使用 PHP 的get_object_vars而不是类型转换对象。

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

回答by Bart B

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.

如果“对象”实际上是一个关联数组而不是真正的对象,那么array_keys()它将为您提供所需的内容,而不会出现警告或错误。

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

另一方面,如果您的对象是真正的对象,那么如果您尝试array_keys()直接使用,则会收到警告。

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():

您可以使用 将对象中的键值对提取为关联数组get_object_vars(),然后您可以使用 从中获取键array_keys()

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