Php 如何从嵌套对象构建嵌套数组?
例如,我有对象:Php 如何从嵌套对象构建嵌套数组?,php,algorithm,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'; $
<?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);
如何构建此阵列?当然,3个对象只是一个例子,这个值可能更大或更小,所以我想我需要递归函数。你是说对象的关联数组?如果是这样,您可以只使用:
$array = (array) $object;
Meaby此答案为您提供了更多信息:
对象结构的转换
{
'objects':[
{
'key':'a1'
},
{
'key':'a2',
'parent':{
'key':'a1'
},
},
{
'key':'a3',
'parent':{
'key':'a2',
'parent':{
'key':'a1'
}
}
}
],
'value':100
}
致:
这不是小事。您必须自己为此创建某种函数。这是一项非常有趣的任务,需要解决!谢谢你的发帖。它仍然不是完美的代码,因为函数中有一个全局变量,但它可以工作。我希望它很简单。我甚至用四个物体来测试它
$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);
我希望这有帮助:另一个解决方案,但没有全局变量:
是否要生成对象,然后使用数组$object对其进行转换?所需的效果尚未充分定义。得出结果是因为父关系还是因为值变量?因为其中一个是多余的。此外,您至少应该尝试提出一个函数的原型,并将其发布到此处。不,我需要的与示例中的完全相同。是的,我正在请求有关构建此函数的帮助=我想我会这样做:在最后一个元素中,递归地用值键替换,例如,parent。但还有其他选择吗?
[
'a1' => ['a2' => ['a3' => 100]]
]
$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);
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);