Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle post multipart request with nested array

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.

like image 463
Danny Bevers Avatar asked Jan 11 '17 09:01

Danny Bevers


1 Answers

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)];
        }
    }
like image 151
Danny Bevers Avatar answered Sep 19 '22 13:09

Danny Bevers