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

时间:2015-02-04 11:04:43

标签: php arrays curl

我正在调用一个函数来从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","","","");

2 个答案:

答案 0 :(得分:0)

尝试使用:array_merge

$a = getData("http://www.example.com/foo.php","","","");
$b = getData("http://www.example.org/bar.php","","","");
$c = getData("http://www.example.net/helloworld.php","","","");

$r = array_merge($a,$b,$c);

答案 1 :(得分:0)

您可以使用此函数http://php.net/manual/en/function.array-merge.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;更改为return $returnedData; echo仅显示它,return将其返回给变量。