-1

I have the follow array of strings:

$arrayOfStrings = [
    0 => "item1",
    1 => "item2",
    2 => "item2.subitem1",
    3 => "item2.subitem2.a",
    4 => "item2.sutitem2.b"
]

And I need to convert this array of strings to multidimensional array, like this:

$multidimensionalArray = [
    0 => "item1",
    "item2" => [
        "subitem1",
        "subitem2" => [
            "a",
            "b"
        ]
    ]
];

1 Answers1

0

I just got it, as follows:

private function createArrayFromString($fields)
    {
        $arrayFields = [];
        foreach ($fields as $k => $field) {
            $field = explode('.', $field);
            $count = count($field);
            if ($count > 1) {
                $parent = $field[0];
                unset($field[0]);
                $nextFields[] = implode('.', $field);
                $arrayFields[$parent] = $this->createArrayFromString($nextFields);
            } else {
                $arrayFields[$k] = $field[0];
            }

        }
        return $arrayFields;
    }