2016-09-22 63 views
2

使用api調用我正在讀取存儲在數組中的一系列數據對象,但我只想打印出返回的一些對象。在數組中訪問顯式對象

所有的數據都存儲在$mail變量中。我期待來訪問交付例如,它會是這樣的$mail->delivered

這是樣本數據恢復 -

""" 
[\n 
    {\n 
    "count_purchased": 0,\n 
    "delivered": 1,\n 
    "clicked_unique": 0,\n 
    "shared": 0,\n 
    "mailings": 1,\n 
    "year": 2016,\n 
    "month": 9,\n 
    "opened": 1,\n 
    "opted_out": 0,\n 
    "sent": 1,\n 
    "signed_up": 0,\n 
    },\n 
    {\n 
    "count_purchased": 0,\n 
    "delivered": 56,\n 
    "clicked_unique": 0,\n 
    "shared": 0,\n 
    "mailings": 31,\n 
    "year": 2016,\n 
    "month": 9,\n 
    "opened": 1,\n 
    "opted_out": 0,\n 
    "sent": 102,\n 
    "signed_up": 0,\n 
    }\n 
] 
+0

是JSON響應? –

回答

2

與解釋一點點加強answer of M. I.

既然你得到一個JSON字符串作爲迴應,你需要將其轉換。方便的是,PHP有一個功能,最明顯的是json_decode

因此,如果您的回覆存儲在$mail中,那麼我們所需要做的就是將其轉換爲associative array或類\stdClass的對象。所以我們需要做一些工作,纔可以訪問它的方式

您的回覆返回多個對象,你把它想:

// Given the content of mail is your given json string 

// The second parameter allows us to use each entry of $mailData as \stdClass. 
// If you want to use an assiocative array instead, you can put in true for the second parameter. 
$mailData = json_decode($mail, false); // false can also be omitted in this case. 
echo $mailData[0]->sent; // 1 
echo $mailData[1]->sent; // 102 

// Now you are able to do fancy stuff with the data, for example loop over it. 
foreach($mailData as $singleMailData) { 
    // Do whatever you want with each entry. In my example I just print out the data. 
    var_dump($singleMailData); 
} 
+0

非常感謝您的解釋,現在也很好理解,以備將來使用! – SamXronn

1

你得到一個JSON作爲響應。用途:

json_decode($jsonString); // to get an `JSON` object or 
json_decode($jsonString, true); // to get an associative array.