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, &$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!