Php 如何将cURL响应合并到一个数组中?

Php 如何将cURL响应合并到一个数组中?,php,arrays,curl,Php,Arrays,Curl,我调用一个函数从3个不同的源获取数据。 $returnedData响应始终是一个数组。如何将所有3个响应合并到一个数组中 function getData($xPostURL,$xToken,$xTokenSecret,$xAccount) { $datatopost = array ( "token" => $xToken, "tokenSecret" => $xTokenSecret, "account" => $

我调用一个函数从3个不同的源获取数据。
$returnedData
响应始终是一个数组。如何将所有3个响应合并到一个数组中

function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{ 
    $datatopost = array (
        "token" =>  $xToken,
        "tokenSecret" => $xTokenSecret,
        "account" => $xAccount,
    );

    $ch = curl_init ($xPostURL);
    curl_setopt ($ch, CURLOPT_POST, true);  
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $returnedData = curl_exec ($ch);

    echo $returnedData;
}

getData("http://www.example.com/foo.php","","","");
getData("http://www.example.org/bar.php","","","");
getData("http://www.example.net/helloworld.php","","","");
试用:


可以使用此函数合并数组 如果我们使用此函数,您的代码将如下所示:

function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{ 
    $datatopost = array (
        "token" =>  $xToken,
        "tokenSecret" => $xTokenSecret,
        "account" => $xAccount,
    );

    $ch = curl_init ($xPostURL);
    curl_setopt ($ch, CURLOPT_POST, true);  
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $returnedData = curl_exec ($ch);

    return $returnedData;
}

$firstData = getData("http://www.example.com/foo.php","","","");
$secondData = getData("http://www.example.org/bar.php","","","");
$thirdData = getData("http://www.example.net/helloworld.php","","","");

$merged = array_merge($firstData, $secondData, $thirdData);
现在所有的东西都是美元
(还做了一些缩进并将
echo$returnedData;
更改为
returnedData;
echo
仅显示它,
return
将它返回到变量。

太棒了,谢谢您的帮助。我需要如何从调用的getData(“)发送数据?我需要使用echo,print\r()或者返回以发送数组而不是字符串?我的代码来自“foo.php”文件:
$resultNames=array();foreach($arr as$row){$resultNames[]=$row['name'];}print\r($resultNames)
@Tom,似乎您正在制作某种API,因此最好从
example.com/*.php
文件返回xml或json响应。您可以通过发送
content-type:application/json
content-type:application/xml
标题,然后以相应的格式回显数据来实现这一点。
function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{ 
    $datatopost = array (
        "token" =>  $xToken,
        "tokenSecret" => $xTokenSecret,
        "account" => $xAccount,
    );

    $ch = curl_init ($xPostURL);
    curl_setopt ($ch, CURLOPT_POST, true);  
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $returnedData = curl_exec ($ch);

    return $returnedData;
}

$firstData = getData("http://www.example.com/foo.php","","","");
$secondData = getData("http://www.example.org/bar.php","","","");
$thirdData = getData("http://www.example.net/helloworld.php","","","");

$merged = array_merge($firstData, $secondData, $thirdData);