【问题标题】:how to map Object property names into an array如何将对象属性名称映射到数组中
【发布时间】:2014-10-22 10:57:08
【问题描述】:

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

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

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

我想得到一个包含所有“离开属性名称”的数组:

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

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

【问题讨论】:

  • 你试过了吗??
  • 您需要这个有什么具体的技术原因吗?可能有更好的选择或更好的设计来实现您的实际业务目标

标签: php php-5.5


【解决方案1】:
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',
)

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 2020-07-21
    • 2020-08-04
    • 1970-01-01
    • 2020-02-10
    • 2012-01-23
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多