2014-10-22 188 views
0

我有一个对象的结构是这样的:如何对象的属性名称映射到一个数组

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

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

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

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

有没有一个简单的方法来做到这一点?

+0

你尝试过什么? – 2014-10-22 11:25:06

+0

有什么特定的技术原因,你为什么需要这个?可能有更好的选择,或更好的设计来实现您的实际业务目标 – 2014-10-22 11:30:05

回答

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', 
) 
相关问题