0

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;
}
2
  • What have you try? Commented Sep 17, 2019 at 0:35
  • 1
    @KrisRoofe I have added the code Commented Sep 17, 2019 at 0:38

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it with this, check the Demo

    function array_format(&$array){
        $temp_array = [];
        foreach($array as $k=>$v){
            $temp_array[] = $k;
            if(is_array($v)){
                array_format($v);
                $temp_array[$k] = $v;
            }
        }
        $array = $temp_array;
    }
    array_format($array);
    print_r($array);

Comments

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.