我有一个像这样的对象结构:
$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',
)