2016-04-14 56 views
0

我正在使用Mailchimp API,并尝试将用户名从我的表单传递给列表。如何通过php正确地发送数据到json?

Mailchimp有一个实际用户名的嵌套结构,我不明白如何为它正确编写代码。

JSON数据结构看起来像这样:

{ 
"email_address": [email protected] 
"merge_fields": { 
"FNAME": 
"LNAME": 
    } 
} 

要使用的功能与POST方法发送POST请求脚本

$result = $MailChimp->post("lists/$mailchimp_list_id/members", [ 
        'email_address' => $subscriber_email, 
        'status'  => 'subscribed', 
        //'merge_fields'['FNAME'] => $subscriber_name; 
      ]); 

我尝试发送'merge_fields'['FNAME'] => $subscriber_name;

人向我解释如何使用PHP进入JSON内部?

+0

如果你不知道更多关于'json',让你的'输入值的阵列structure'在PHP和使用'json_encode()'获取数据json格式。 – Yash

+0

尝试像这样json_encode(array('test'=>'value1')); json_encode会将你的数组转换成json格式 –

+0

其实JSON是从mailchimp返回给你的,或者是什么mailchimp作为输入要求的?在我回答 – RiggsFolly

回答

0

尝试这样

$jsonArray = json_encode(array('0' =>'test','1' => 'test2')); 

json_encode将你的php数组转换成JSON格式
如果你想解码你的JSON数组PHP数组,然后使用json_decode

$phpArray = json_decode('Any json encoded array'); 
0

首先创建一个PHP数据结构匹配所需的JSON结构,然后结构为json_encode()

{}指物体在JSON 的[]意味着JSON阵列

<?php 
    $inner = new stdClass(); 
    $inner->FNAME = $subscriber_first_name; 
    $inner->LNAME = $subscriber_last_name; 


    $member = new stdClass(); 
    $member->email_address = '[email protected]'; 
    $member->merge_fields = $inner; 

    $json_string = json_encode($member); 
+0

之前应该询问这个问题我的代码如下:“email_address”:“xxx @ gmail。com“,”merge_fields“:{”FNAME“:”Igor“},”status“:”订阅“,但由于某种原因,它没有通过Mailchimp验证( –

+0

对不起,我无法帮助MailChimp部分, it – RiggsFolly

+0

This code worked:$ result = $ MailChimp-> post(“lists/$ mailchimp_list_id/members”,[ 'email_address'=> $ subscriber_email, 'status'=>'subscribed', 'merge_fields'=>阵列( “FNAME” => $ subscriber_name, “LNAME” =>空, ), ]); –

0

好吧,这是PHP与JSONs工作的最佳方式:

  1. 添加此得到全JSON正文:

    $json = file_get_contents('php://input'); 
    
  2. 验证json。我使用Respect Validator进行工作。 https://github.com/Respect/Validation/blob/master/docs/Json.md

     if(v::json()->validate($json)){ 
    
          $whatever = new whatever($json); 
         } 
    
  3. 与规范化PHP类 类无论{ 公共$电子邮件JSON对象; public $ merged_fields;

    function __construct($json){ 
         $json = json_decode($json); 
    
         if($json->email){ 
          $this->email = $json->email  
         }else{ 
          echo "Error";  
         } 
        } 
    } 
    
  4. 使用jsonSerializable进行编码。这是一个非常好的方法文档: http://www.sitepoint.com/use-jsonserializable-interface/

相关问题