问题
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);
}
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?
回答1:
DataObjects
in SilverStripe represent a record from the database, in your case you wound use a ArrayData
.
Use $array = Convert::json2array($returnTwitter)
or $array = json_decode($returnTwitter, true)
instead.
and see https://stackoverflow.com/a/17922260/1119263 for how to use ArrayData
回答2:
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);
}
来源:https://stackoverflow.com/questions/19888110/silverstripe-convert-twitter-json-string-to-dataobject-to-loop-though-in-templa