在 php 中遍历数组的具体问题

Specific problem with traversing an array in php

我给了数组:

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

需要转换成这个:

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

循环应该检查一个值是否是一个数组,如果是,它应该将键作为一个值(0 => category)添加到数组的根,然后保持键原样(category => ...) 并再次遍历该值以构建树,如示例所示。

我被这个问题困住了,每次尝试时,我都会得到错误的结果。是否有人是阵列大师并且知道如何简单地做到这一点?

目前的代码:

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;
}

你可以这样做,检查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);

你可以使用 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;
  });
}

演示:https://3v4l.org/3BfKD