Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

php - Post multidimensional array using CURL and get the result on server

I am sending data from my local machine to server using CURL. And the data is multidimensional array.

Array
(
[0] => stdClass Object
    (
        [id] => 1
    )
[1] => stdClass Object
    (
        [id] => 0
    )
[2] => stdClass Object
    (
        [id] => 11
    )
)

I am using this below code for sending the data.

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "my_url");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);  // $array is my above data

But at server when I try to put this incoming data to file or just print_r it gives me this below output

Array
(
[0] => Array
[1] => Array
[2] => Array
)

But I want the output in multidimensional.

I tried with print_r($_POST[0]) but it gives only Array text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

cURL can only accept a simple key-value paired array where the values are strings, it can't take an array like yours which is an array of objects. However it does accept a ready made string of POST data, so you can build the string yourself and pass that instead:

$str = http_build_query($array);

...

curl_setopt($ch, CURLOPT_POSTFIELDS, $str);

A print_r($_POST) on the receiving end will show:

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 0
        )

    [2] => Array
        (
            [id] => 11
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...