Created
April 30, 2020 19:54
-
-
Save vluzrmos/620d8804bbaa5422b6bfa47c4813bd5d to your computer and use it in GitHub Desktop.
PHP Multipart array to Guzzle Client or other ...
This file contains hidden or 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 | |
/** | |
* Turns associative arrays into multipart [['name' => 'key[0][deep]', 'contents' => 'value']] | |
*/ | |
function array_multipart(array $data = []) | |
{ | |
$dots = array_dot($data); | |
$multipart = []; | |
foreach ($dots as $key => $content) { | |
$multipart[] = [ | |
'name' => bracket_from_dots($key), | |
'contents' => $content | |
]; | |
} | |
return $multipart; | |
} | |
/** | |
* Flatten a multi-dimensional associative array with dots. | |
* | |
* @param iterable $array | |
* @param string $prepend | |
* @return array | |
*/ | |
function array_dot($array, $prepend = '') | |
{ | |
$results = []; | |
foreach ($array as $key => $value) { | |
if (is_array($value) && ! empty($value)) { | |
$results = array_merge($results, array_dot($value, $prepend.$key.'.')); | |
} else { | |
$results[$prepend.$key] = $value; | |
} | |
} | |
return $results; | |
} | |
function bracket_from_dots($key) | |
{ | |
$segments = explode('.', $key); | |
$result = array_shift($segments); | |
foreach ($segments as $name) { | |
$result .= "[{$name}]"; | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment