【问题标题】:How to merge cURL responses into one array?如何将 cURL 响应合并到一个数组中?
【发布时间】:2015-02-04 11:04:43
【问题描述】:

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

【问题讨论】:

    标签: php arrays curl


    【解决方案1】:

    尝试使用: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);
    

    【讨论】:

      【解决方案2】:

      您可以使用此功能合并数组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);
      

      现在一切都在 $merged (也做了一些缩进,把echo $returnedData;改成return $returnedData;echo只显示它,return把它返回给变量。

      【讨论】:

      • 太棒了,感谢您的帮助。我如何需要从被调用的 getData("example.com/…); 发送数据?我是否需要使用 echo、print_r() 或 return 来发送数组而不是字符串?我的代码来自“foo. php”文件:$resultNames = array(); foreach($arr as $row){ $resultNames[] = $row['name']; } print_r($resultNames);
      • @Tom,您似乎正在制作某种 API,因此最好从 example.com/*.php 文件返回 xml 或 json 响应。您可以通过发送例如content-type:application/jsoncontent-type:application/xml 标头然后以相应格式回显您的数据来实现此目的。
      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多