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

时间:2014-10-22 10:57:09

标签: php php-5.5

我有一个像这样的Object结构:

$o = new stdClass();
$o->f1 = new stdClass();
$o->f2 = 2;

$o->f1->f12 = 5;
$o->f1->f13 = "hello world";

我想获得所有“离开属性”名称的数组:

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

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:0)

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',
)