本文介绍了Silverstripe:将twitter JSON字符串转换为Dataobject以在模板中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用twitter API获取一个时间轴,该时间轴我想通过我的模板输出.我正在这样获取提要:

I'm using the twitter API to get a timeline which I want to output through my template. I'm getting the feed like so:

public static function getTwitterFeed(){
    $settings = array(
        'oauth_access_token' => "xxx",
        'oauth_access_token_secret' => "xxx",
        'consumer_key' => "xxx",
        'consumer_secret' => "xxx"
    );

    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name=xxx&count=5';
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $returnTwitter = $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();
    return json_decode($returnTwitter);

}

这将返回一个对象数组(tweet是对象),我希望能够像这样在模板中循环遍历它:

This returns an array of objects (the tweet is the object) and I want to be able to loop through it in my template like so:

<% loop TwitterFeed %>
    <h4>$created_at</h4>
    <p>$text</p>
<% end_loop %>

正如我上面提到的,循环被输入一次,但是没有识别出任何值.我该如何实现?

As I have it above, the loop is entered once but no values are recognised. How can I achieve this?

推荐答案

感谢Zauberfisch向我指出正确的方向.我是这样解决的:

Thanks to Zauberfisch for pointing me in the right direction. I solved it like so:

public static function getTwitterFeed(){
    $settings = array(
        'oauth_access_token' => "xxx",
        'oauth_access_token_secret' => "xxx",
        'consumer_key' => "xxx",
        'consumer_secret' => "xxx"
    );

    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name=xxx&count=5';
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $returnTwitter = $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();

    $returnTwitter = Convert::json2array($returnTwitter);

            $tweets = array();
            foreach ($returnTwitter as $key => $value) {
                $tweets[] = new ArrayData(array('created_at' => $value['created_at'], 'text' => $value['text']));


            }
                return new ArrayList($tweets);

    }

这篇关于Silverstripe:将twitter JSON字符串转换为Dataobject以在模板中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 13:00