Last active
July 5, 2018 08:56
-
-
Save matthew-inamdar/a17701f948770ac0a55acd9d12445645 to your computer and use it in GitHub Desktop.
Flatten Multidimensional Array to HTML Input Name Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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