Skip to content

Instantly share code, notes, and snippets.

@matthew-inamdar
Last active July 5, 2018 08:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthew-inamdar/a17701f948770ac0a55acd9d12445645 to your computer and use it in GitHub Desktop.
Save matthew-inamdar/a17701f948770ac0a55acd9d12445645 to your computer and use it in GitHub Desktop.
Flatten Multidimensional Array to HTML Input Name Array
<?php
use Illuminate\Http\UploadedFile;
class Flatten
{
/**
* Used for turning an array into a PHP friendly name.
*
* @param array $array
* @param string $prefix
* @param string $suffix
* @return array
*/
protected function flatten(array $array, string $prefix = '', string $suffix = ''): array
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $this->flatten($value, $prefix . $key . $suffix . '[', ']'));
} else {
if ($value instanceof UploadedFile) {
$result[] = [
'name' => $prefix . $key . $suffix,
'filename' => $value->getClientOriginalName(),
'Mime-Type' => $value->getClientMimeType(),
'contents' => file_get_contents($value->getPathname()),
];
} else {
$result[] = [
'name' => $prefix . $key . $suffix,
'contents' => $value,
];
}
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment