Skip to content

Instantly share code, notes, and snippets.

@maxcelos
Created December 29, 2021 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcelos/6f1b8acd45d97068bceb4c5d4f5f61da to your computer and use it in GitHub Desktop.
Save maxcelos/6f1b8acd45d97068bceb4c5d4f5f61da to your computer and use it in GitHub Desktop.
Convert multidimensional array to simple array with keys
flatten(array $array, $keyPrefix = ''): array
{
    $return = [];

    foreach ($array as $key => $value) {
        $key = trim($keyPrefix . '_' . $key, '_');

        if (is_array($value)){
            $return = array_merge($return, flatten($value, $key));
        } else {
            $return[$key] = $value;
        }
    }

    return $return;
}

Screen Shot 2021-12-29 at 09 59 28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment