0

I've been hours trying to figure this, i know i'm missing something obvious. This is the problem:

I have an array that some of its elements are objects, others are arrays and others are of other types. What i need is:

  • Loop through the array and convert the object elements into array elements.
  • Loop recursively (or whatever you want to call it) through these new array elements (the ones that were converted from objects) and the elements that already are array and perform the previous task (that is: convert the object elements into array elements).

Here's the gotcha: every time an object element is converted into array, the class name of the object has to be added as the first element of the array that is generated by converting the object.

Here is a simplified example:

Array:

Array
(
    [0] => PhpParser\Node\Expr\Assign Object
        (
            [var] => PhpParser\Node\Expr\Variable Object
                (
                    [name] => bar

                )

            [expr] => PhpParser\Node\Scalar\LNumber Object
                (
                    [value] => 22

                )


        )

)

I need a function like this:

//$arr is the array previously posted

$arr = cool_object_to_array($arr);

var_dump($arr );

outputs

Array
(
    [0] => Array
        (
            [0] => PhpParser\Node\Expr\Assign
            [var] => Array
                (
                    [0] => PhpParser\Node\Expr\Variable 
                    [name] => bar

                )

            [expr] =>Array 
                (
                   [0] => PhpParser\Node\Scalar\LNumber
                   [value] => 22

                )


        )

)

The nesting level is unknown. It can be many arrays nested on objects nested on other objects or arrays, etc. The example is just very simplified. I need a solution that handles that too.

Thanks in advance for all your answers!

1 Answer 1

1

This should do it:

function cool_object_to_array($array) {
  foreach ($array as $key => &$value) {
    if (is_object($value)) {
      $type = get_class($value);
      $value = (array) $value;
      array_unshift($value, $type);
    }
    if (is_array($value)) {
      $value = cool_object_to_array($value);
    }
  }
  return $array;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man!! It works like a charm. I wrote a function that looked a lot like this myself, but i was missing the reference operator, plus i was calling the function revursively on the first "if" block, which made the whole thing work wrong. You saved my day, (and i think i learned something about loops and arrays)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.