通过desk.com API的JSON响应循环

时间:2013-10-16 03:32:05

标签: php json api

我对JSON解码比较陌生,但我已经能够使用这种格式(见下文)进行循环,但它似乎不适用于desk.com api。不确定是不是因为JSON响应的复杂性与我的格式不一样,或者有更好的方法来获取key->值对。

以下是此API调用的JSON响应(http://dev.desk.com/API/topics/#list):

{"total_entries":4,"_links":{"self":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"first":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"last":{"href":"/api/v2/topics?page=1&per_page=50","class":"page"},"previous":null,"next":null},"_embedded":{"entries":[{"name":"Privacy & Security","description":"Information about your privacy.","position":1,"allow_questions":false,"in_support_center":true,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-09-26T00:12:13Z","_links":{"self":{"href":"/api/v2/topics/445877","class":"topic"},"articles":{"href":"/api/v2/topics/445877/articles","class":"article"},"translations":{"href":"/api/v2/topics/445877/translations","class":"topic_translation"}}},{"name":"Canned Responses","description":"Internal responses to common questions","position":3,"allow_questions":true,"in_support_center":false,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-09-26T00:31:25Z","_links":{"self":{"href":"/api/v2/topics/445878","class":"topic"},"articles":{"href":"/api/v2/topics/445878/articles","class":"article"},"translations":{"href":"/api/v2/topics/445878/translations","class":"topic_translation"}}},{"name":"FAQ","description":"Frequently Asked Questions","position":2,"allow_questions":false,"in_support_center":true,"created_at":"2013-02-10T04:40:05Z","updated_at":"2013-10-15T00:47:09Z","_links":{"self":{"href":"/api/v2/topics/445879","class":"topic"},"articles":{"href":"/api/v2/topics/445879/articles","class":"article"},"translations":{"href":"/api/v2/topics/445879/translations","class":"topic_translation"}}},{"name":"Suggestions & Feedback","description":"","position":4,"allow_questions":true,"in_support_center":true,"created_at":"2013-07-03T05:27:56Z","updated_at":"2013-10-16T02:38:11Z","_links":{"self":{"href":"/api/v2/topics/538220","class":"topic"},"articles":{"href":"/api/v2/topics/538220/articles","class":"article"},"translations":{"href":"/api/v2/topics/538220/translations","class":"topic_translation"}}}]}}

以下是解码和循环以获取NAME值的方法:

$topics = json_decode($response);

foreach ($topics as $topic) {
    echo "Name: " . $topic->_embedded->entries->name;
}  

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你走了:

$entries = $topics->_embedded->entries; // 'entries' from the json response is an array. 
$i = 0;
while(isset($entries[$i])) { // Loop through the array to pick up all the data you need 
 $data[$i][0] = $entries[$i]->name;
 $data[$i][1] = $entries[$i]->description;
 $data[$i][2] = $entries[$i]->_links->self->href;
 $i++;
}
var_dump($data) // Array with all the data. Note that this is now a 2-d array.

让我知道这是否有效