Search code examples
phparraystraversal

Specific problem with traversing an array in php


I have given the array:

array(
   "firstName": null,
   "lastName": null,
   "category": [
        "name": null,
        "service": [
           "foo" => [
               "bar" => null
           ]
        ]
   ]
)

that needs to be transform into this:

array(
    0 => "firstName",
    1 => "lastName",
    2 => "category",
    "category" => [
        0 => "name",
        1 => "service",
        "service" => [
             0 => "foo",
             "foo" => [
                  0 => "bar"
             ]
        ]
    ]
)

The loop should check if a value is an array and if so, it should add the key as a value (0 => category) to the root of array and then leave the key as it is (category => ...) and traverse the value again to build the tree as in example.

I am stuck with this and every time I try, I get wrong results. Is there someone who is array guru and knows how to simply do it?

The code so far:

private $array = [];
private function prepareFields(array $fields):array
{
    foreach($fields as $key => $value)
    {
        if(is_array($value))
        {
            $this->array[] = $key;
            $this->array[$key] = $this->prepareFields($value);
        }
        else
        {
            $this->array[] = $key;
        }
    }

    return $this->array;
}

Solution

  • You could make use of array_reduce:

    function prepareFields(array $array): array
    {
      return array_reduce(array_keys($array), function ($result, $key) use ($array) {
        $result[] = $key;
        if (is_array($array[$key])) {
          $result[$key] = prepareFields($array[$key]);
        }
        return $result;
      });
    }
    

    Demo: https://3v4l.org/3BfKD