如何将Object属性名称映射到数组中


how to map Object property names into an array

我有一个这样的对象结构:

$o = new stdClass();
$o->f1 = new stdClass();
$o->f2 = 2;
$o->f1->f12 = 5;
$o->f1->f13 = "hello world";

我想得到一个所有"保留属性名称"的数组:

$a = ["f2","f1f12", "f1f13"]

有简单的方法吗?

function getObjectVarNames($object, $name = '')
{
    $objectVars = get_object_vars($object);
    $objectVarNames = array();
    foreach ($objectVars as $key => $objectVar) {
        if (is_object($objectVar)) {
            $objectVarNames = array_merge($objectVarNames, getObjectVarNames($objectVar, $name . $key));
            continue;
        }
        $objectVarNames[] = $name . $key;
    }
    return $objectVarNames;
}
$o = new stdClass();
$o->f1 = new stdClass();
$o->f2 = 2;
$o->f1->f12 = 5;
$o->f1->f13 = "hello world";
var_export(getObjectVarNames($o));

结果:

array (
  0 => 'f1f12',
  1 => 'f1f13',
  2 => 'f2',
)