首页 > 解决方案 > PHP索引数组到嵌套关联数组

问题描述

我需要根据特定规则将简单数组转换为嵌套数组。我已经实现了,但我正在寻找更好的解决方案。

简单的:

array(4) {
  [0]=>
  array(2) {
    ["id"]=>
    string(2) "11"
    ["type"]=>
    int(3)
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(2) "10"
    ["type"]=>
    int(2)
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(1) "1"
    ["type"]=>
    int(1)
  }
  [3]=>
  array(2) {
    ["id"]=>
    string(1) "0"
    ["type"]=>
    int(1)
  }
}

预期效果:

array(1) {
  [0]=>
  array(2) {
    ["type"]=>
    int(1)
    ["child"]=>
    array(1) {
      [1]=>
      array(2) {
        ["type"]=>
        int(1)
        ["child"]=>
        array(1) {
          [10]=>
          array(2) {
            ["type"]=>
            int(2)
            ["child"]=>
            array(1) {
              [11]=>
              array(2) {
                ["type"]=>
                int(3)
                ["child"]=>
                array(0) {
                }
              }
            }
          }
        }
      }
    }
  }
}

我的解决方案(不是很满意):

$nestedArray = [];
    foreach ($simpleArray as $item)
    {
        if (!empty($nestedArray))
        {
            $array = $nestedArray;
            reset($array);
            $firstKey = key($array);
        }
        $nestedArray[$item['id']]['child'] = $nestedArray;
        $nestedArray[$item['id']]['type'] = $item['type'];
        if (!empty($firstKey))
        {
            unset($nestedArray[$firstKey]);
        }
    }

正如我所说,我正在寻找更优雅的方式来实现这一目标。规则非常简单:每个下一个项目都是前一个的孩子。

标签: phparraysmultidimensional-arrayconverter

解决方案


你可以使用递归:

function nest($arr) {
    return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}

使用您的示例输入,它看起来像这样:

$simpleArray = [
    ["id" => "11", "type" => 3],
    ["id" => "10", "type" => 2],
    ["id" => "1", "type" => 1],
    ["id" => "0", "type" => 1]
];

function nest($arr) {
    return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}

$nested = nest($simpleArray));

$nested将具有以下值:

[
    "type" => 1,
    "child" => [
        "type" => 1,
        "child" => [
            "type" => 2,
            "child" => [
                "type" => 3,
                "child" => []
            ]
        ]
    ]
]

推荐阅读