0

For example, I have objects:

<?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);

In result I need to get array like this:

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

How can I build this array? Of Course 3 objects is just an example, this value may be bigger or smaller, so I need recursive function I think.

engilexial
  • 153
  • 1
  • 3
  • 14
  • You want to build your object and then convert it with (array) $object? – Matt Jul 27 '17 at 14:26
  • The desired effect is not sufficiently defined. Do you arrive at your result because of the parent relations or because of the value variable? Because one of these is redundant. Also you should at least try to come up with a prototype of your function and post it here. – Kempeth Jul 28 '17 at 06:09

4 Answers4

1

Another solution but without the global variable:

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);
0

You mean associative array from object? If so You can use just:

$array = (array) $object;

Meaby this answer give You more information:

Convert PHP object to associative array

0

The conversion from your object structure

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

to:

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

is non-trivial. You'll have to create some kind of function for this yourself.

Kempeth
  • 1,856
  • 2
  • 22
  • 37
0

This was a very interesting task to solve! Thanks for posting. It is still not the perfect code because there is a global variable in the function but it works. I hope it is simple. I tested it even with four objects.

$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);

I hope that helped :)