2016-04-14 58 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/

相關問題