Home  >  Article  >  Backend Development  >  How to Submit Multidimensional Array Data via PHP and CURL?

How to Submit Multidimensional Array Data via PHP and CURL?

Susan Sarandon
Susan SarandonOriginal
2024-10-23 08:19:29757browse

How to Submit Multidimensional Array Data via PHP and CURL?

Resolving Multidimensional Array Posting with PHP and CURL

When submitting a form using CURL to a remote PHP script, issues may arise when dealing with multidimensional array data. An "Array to string conversion" error often occurs due to the unsupported structure in CURLOPT_POSTFIELDS.

One way to tackle this challenge is to utilize a custom function, such as the one provided in the response:

<code class="php">function http_build_query_for_curl( $arrays, &amp;$new = array(), $prefix = null ) {

    if ( is_object( $arrays ) ) {
        $arrays = get_object_vars( $arrays );
    }

    foreach ( $arrays AS $key => $value ) {
        $k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key;
        if ( is_array( $value ) OR is_object( $value ) ) {
            http_build_query_for_curl( $value, $new, $k );
        } else {
            $new[$k] = $value;
        }
    }
}</code>

This function takes an array as input and recursively flattens it, creating a new array where each value is assigned to a specific key. By passing the arrays to be posted to this function, we obtain a modified array with a compatible structure for CURLOPT_POSTFIELDS.

<code class="php">$arrays = array(
    'name' => array(
        'first' => array(
            'Natali', 'Yura'
        )
    )
);

http_build_query_for_curl( $arrays, $post );</code>

By using the modified $post array, which has a flattened structure, we can successfully submit the multidimensional data via CURL without encountering the conversion error:

<code class="php">curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);</code>

The above is the detailed content of How to Submit Multidimensional Array Data via PHP and CURL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn