Array parameters can be passed through POST in PHP. Usually, when multiple values or large amounts of data need to be passed, it is more convenient to use arrays for parameter passing.
There are many ways to pass array parameters using POST. This article will introduce two of them in detail.
First way: Use the http_build_query function to convert the array into a string for transmission
The http_build_query function can convert the array into a URL string. You can use this function to convert the array into a URL query character. string and then send it as a parameter of the POST request.
Sample code:
<?php // 定义一个数组 $data = array( 'name' => '张三', 'age' => 20, 'gender' => '男' ); // 转换数组为URL查询字符串 $queryString = http_build_query($data); // 初始化curl $ch = curl_init(); // 设置请求的url curl_setopt($ch, CURLOPT_URL, 'http://localhost/example.php'); // 设置请求方式为POST curl_setopt($ch, CURLOPT_POST, 1); // 设置POST参数 curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString); // 执行POST请求 curl_exec($ch); // 关闭curl curl_close($ch); ?>
In the above code, we convert an array containing name, age and gender into a URL query string, and then use the curl library to send a POST request.
Second way: Use JSON format to pass array parameters
In PHP, we can use tools such as Postman to send POST requests in JSON format, so we can use JSON format to pass parameters containing arrays .
Sample code:
<?php // 定义一个数组 $data = array( 'name' => '张三', 'age' => 20, 'gender' => '男' ); // 将数组转换为JSON格式 $jsonData = json_encode($data); // 初始化curl $ch = curl_init(); // 设置请求的url curl_setopt($ch, CURLOPT_URL, 'http://localhost/example.php'); // 设置POST请求的Content-Type为application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // 设置请求方式为POST curl_setopt($ch, CURLOPT_POST, 1); // 设置POST参数为JSON格式 curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // 执行POST请求 curl_exec($ch); // 关闭curl curl_close($ch); ?>
In the above code, we use the json_encode() function in PHP to convert the array into JSON format, and then set the Content-Type of the POST request to application/json, and The POST parameter is set to the converted JSON string.
Summary
In PHP, using POST to pass array parameters is a very common requirement. This article introduces two common ways, that is, using the http_build_query function to convert the array into a query string. and delivered using JSON format. I wish you can be comfortable in actual development and successfully complete your project.
The above is the detailed content of Can post in PHP pass array parameters?. For more information, please follow other related articles on the PHP Chinese website!