Posting multidimensional array with PHP and CURL

前端 未结 8 2054
难免孤独
难免孤独 2020-11-27 06:29

I\'m having trouble posting form data via CURL to a receiving PHP script located on a different host.

I get an Array to string conversion error

8条回答
  •  春和景丽
    2020-11-27 06:29

    First I would like to thank Daniel Vandersluis for his insightful reply. Based on his input I came up with this to fix the problem from the original question:

     $value) {
        $final_key = $prefix ? "{$prefix}[{$key}]" : $key;
        if (is_array($value)) {
          // @todo: handle name collision here if needed
          $output += curl_postfields_flatten($value, $final_key);
        }
        else {
          $output[$final_key] = $value;
        }
      }
      return $output;
    }
    

    Usage should look like this:

    curl_setopt($this->ch, CURLOPT_POSTFIELDS, curl_postfields_flatten($post));
    

    This function will convert arrays like this:

    array(
      'a' => 'a',
      'b' => array(
        'c' => array(
          'd' => 'd',
          'e' => array(
            'f' => 'f',
          ),
        ),
      ),
    );
    

    Into this:

    array(
      'a' => 'a',
      'b[c][d]' => 'd',
      'b[c][e][f]' => 'f',
    )
    

    It doesn't handle cases with mixed format when there is a key collision like this:

    array(
     'b[c]' => '1',
     'b' => array(
       'c' => '2', 
      ),
    );
    

    The output will contain only the first value for that key

    array(
     'b[c]' => '1'
    )
    

提交回复
热议问题