Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

specific function to Unflatten array

/**
     * @param array|string $data Inserted data, like regular array, or simple string(will return as is)
     * @param string $separator string separator to know what we had.
     * @return array|string
     */
    public static function unFlatArr($data, $separator = '_')
    {
        $return = [];

        if (is_iterable($data)) {
            foreach ($data as $oldKey => $value) {
                $keysArr = explode($separator, $oldKey, 2);
                $key = $keysArr[0];
                $k = $keysArr[1] ?? null;

                if (null !== $k) {
                    //got nesting.
                    $value = self::unFlatAr([$k => $value], $separator);
                }
                $return[$key] = is_array($return[$key] ?? null) ? array_merge($return[$key], $value) : $value;
            }

        } else {
            $return = $data;
        }

        return $return;
    }
 
PREVIOUS NEXT
Tagged: #specific #function #Unflatten #array
ADD COMMENT
Topic
Name
5+4 =