如何从嵌套对象构建嵌套数组?

时间:2017-07-27 14:24:25

标签: php algorithm

例如,我有对象:

<?php

class A
{
    public $key;
    public $parent;
}

class B
{
    public $value;
    public $objects;
}

$a1 = new A();
$a1->key = 'a1';
$a2 = new A();
$a2->key = 'a2';
$a2->parent = $a1;
$a3 = new A();
$a3->key = 'a3';
$a3->parent = $a2;

$b = new B();
$b->objects = [$a1, $a2, $a3];
$b->value = 100;
someFunction($b);

结果我需要得到这样的数组:

[
'a1' => ['a2' => ['a3' => 100]]
]

如何构建此数组?当然,3个对象只是一个例子,这个值可能更大或更小,所以我认为我需要递归函数。

4 个答案:

答案 0 :(得分:1)

另一种解决方案,但没有全局变量:

function nested($ob, $val, $res){
  if($res == array()) {
    $res = $val;
  }
  $res = array($ob->key => $res);
  if( is_object($ob->parent) ){  
    $res = nested( $ob->parent, $val, $res);
  }
  return($res);
} 

$res = nested($b->objects[count($b->objects) - 1], $b->value, array());

echo("<pre>");
print_r($b);
print_r($res);

答案 1 :(得分:0)

你的意思是来自对象的关联数组?如果是这样你只能使用:

$array = (array) $object;

Meaby这个答案为您提供了更多信息:

Convert PHP object to associative array

答案 2 :(得分:0)

从对象结构转换

{
  'objects':[
    {
      'key':'a1'
    },
    {
      'key':'a2',
      'parent':{
        'key':'a1'
      },
    },
    {
      'key':'a3',
      'parent':{
        'key':'a2',
        'parent':{
          'key':'a1'
        }
      }
    }
  ],
  'value':100
}

为:

[
'a1' => ['a2' => ['a3' => 100]]
]

非常重要。你必须自己创造一些功能。

答案 3 :(得分:0)

这是一个非常有趣的任务要解决!谢谢发帖。它仍然不是完美的代码,因为函数中有一个全局变量,但它有效。我希望它很简单。我用四个物体测试了它。

$res = array();

function nested($ob, $val){
  global $res;

  if($res == array()) {
    $res = $val; // Set the deepest value in the array to $val
  }
  // Form: put a new array around the old
  $res = array($ob->key => $res); 
  if( is_object($ob->parent) ){  
    nested( $ob->parent, $val); // parent -> go deeper
  }
} 

nested($b->objects[count($b->objects) - 1], $b->value);

echo("<pre>");
print_r($b);
print_r($res);

我希望有所帮助:)