在CURL中传递多个JSON值

时间:2013-09-13 08:46:20

标签: php json curl

我有一个如下的卷曲请求:

curl -d 'api_user=your_sendgrid_username&api_key=your_sendgrid_password&list=my_list&data[]={"email":"address1@domain.com","name":"contactName1"}&data[]={"email":"address2@domain.com","name":"contactName2"}' https://sendgrid.com/api/newsletter/lists/email/add.json

现在我使用以下php代码发布

if(mysql_num_rows($res) > 0) {
    $data = array();
    while($new_signups = mysql_fetch_assoc($res)){
        $data['email'] = $new_signups['uEmail'];
        $data['name'] = $new_signups['firstName']." ".$new_signups['lastName'];
    }
}
$params = array(
    'api_user'  => $sengrid_user,
    'api_key'   => $sendgrid_pass,
    'list' =>'TestAlwin',
    'data' =>json_encode($data)
  );
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $request);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
curl_close($ch);

但这只会照顾到最后的结果。如何传递上面curl请求中给出的更多数据值?或者我需要在循环中运行卷曲传输?

2 个答案:

答案 0 :(得分:0)

您可以创建数据的多维数组。每个数组值都包含另一个包含电子邮件和名称数据的数组:

$c=1;
while($new_signups = mysql_fetch_assoc($res)){

    $data[$c]['email'] = $new_signups['uEmail'];
    $data[$c]['name'] = $new_signups['firstName']." ".$new_signups['lastName'];
    $c++;

}

所以你的数据会是这样的:

array(
   1 => array(
      'email' => 'test@test.nl',
      'name' => 'John'

   ),
   2 => array(
      'email' => 'test@gmail.com',
      'name' => 'Jack'

   ),
)

答案 1 :(得分:0)

您正在覆盖您的数据阵列总是试试这个

//multiple array
$data1 = array()


if(mysql_num_rows($res) > 0) {

    while($new_signups = mysql_fetch_assoc($res)){
        $data = array();
        $data['email'] = $new_signups['uEmail'];
        $data['name'] = $new_signups['firstName']." ".$new_signups['lastName'];
    //bind your single array here
    $data1[] = $data;
    }
}
$params = array(
    'api_user'  => $sengrid_user,
    'api_key'   => $sendgrid_pass,
    'list' =>'TestAlwin',
    'data' =>json_encode($data1)
  );