@ganjo888

Как использовать array undot?

Есть массив
$array = [
 "field1" => [
      "test.name" => "tratata",
 ],
 "field2" => ["id","url"]
];


$result возвращает тот же массив
Не могу сделать так, чтобы "test.name" развернулся как ассоциативный массив и получить следующее
$array = [
     "field1" => [
          "test" => [
                "name" => "tratata",
             ],
       ],
     "field2" => ["id","url"],
   ];


Мой код
function array_undot($dottedArray)
    {
        $array = [];
        foreach ($dottedArray as $key => $value) {
            if (is_array($value)) {
                $this->array_undot($value);
            }
            $this->arraySet($array, $key, $value);
        }

        return $array;
    }

    private function arraySet(&$array, $key, $value)
    {
        if (is_null($key)) {
            return $array = $value;
        }

        $keys = explode('.', $key);

        while (count($keys) > 1) {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if (!isset($array[$key]) || !is_array($array[$key])) {
                $array[$key] = [];
            }

            $array = &$array[$key];
        }

        $array[array_shift($keys)] = $value;

        return $array;
    }

$result = $this->array_undot($array);
  • Вопрос задан
  • 91 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы