After a long day of debugging and try and error tries searching for a good method with Guzzle6 post with nested array and resource items.
I've found on Guzzle6 documentation that data need to be post with ['multipart' => []]. This works when i got single array items. But i got nested array items like this.
[
[firstname] => 'Danny',
[phone] => [
[0] => [
[phone] => 0612345678
]
]
[picture] => '/data/...'
]
This needs to be format as multipart for Guzzle6 as below.
[
[
'name' => 'firstname',
'contents' => 'Danny'
],
[
'name' => 'phone[0][phone]
'contents' => '0612345678'
],
[
'name' => 'picture',
'contents' => fopen('....', 'r')
]
]
I want to fix this without special tricks. Is there a good way to send a post array with nested array and resource to multipart array.
After a full day of work i got my multipart form data array. For everyone with the same problem here's the code. In $output there's a array of fields within data. It can be used in ['multipart' => $output] with Guzzle.
$output = [];
foreach($data as $key => $value){
if(!is_array($value)){
$output[] = ['name' => $key, 'contents' => $value];
continue;
}
foreach($value as $multiKey => $multiValue){
$multiName = $key . '[' .$multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '' ) . '';
$output[] = ['name' => $multiName, 'contents' => (is_array($multiValue) ? reset($multiValue) : $multiValue)];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With