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?
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
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);
}
Related
I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.
I have a text data file called "poduct_data.txt"
id | name | top
------------------
id01-- name01-- top
id02-- name02--
id03-- name03--
id04-- name04-- top
id05-- name05-- top
id06-- name06--
id07-- name07-- top
id08-- name08--
id09-- name09--
id10-- name10-- top
Here is 3 columns called id,name&top.
"my task is :
to find top column data from this text file and
display them randomly by three top data when reload page."
like: name01 name04 name 05
if reload page then show randomly another 3 data
may be : name07 name05 name10
Every time reload page show different 3 data from top data
1 is done and displaying like: name01 name10 name04 name07 name 05
but having problem in 2.
My work files are in below:
library file : ProductLib.pm
package ProductLib;
use strict;
use File::Basename;
use FileHandle;
use Encode;
use CGI;
use POSIX;
use Date::Parse;
sub new {
my $class = shift;
my ($ProgramName, $ProgramPath, undef) = fileparse($0);
my $self = {
'program_name' => $ProgramName,
'program_path' => $ProgramPath,
'data_dir' => 'data',
'product_data_file' => 'product_data.txt',
'template_dir' => 'templates',
'template' => {},
'cgi' => new CGI(),
#_,
};
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
$Data::Dumper::Terse = 1;
return bless $self, $class;
}
sub SearchRandomProduct{
my $self = shift;
my $TargetTop = shift;
my $ProductHash = $self->GetProductData();
my $TargetProduct = {};
foreach my $ProductId (sort {$a cmp $b} (keys %{$ProductHash})){
my $ProductData = $ProductHash->{$ProductId};
my $ProductTop = $ProductData->{'top'};
next if(defined $TargetTop && $ProductTop ne $TargetTop);
$TargetProduct->{$ProductId} = $ProductData;
}
return $TargetProduct;
}
sub GetProductData{
my $self = shift;
my $FilePath = sprintf('%s/%s',
$self->{'data_dir'},
$self->{'product_data_file'}
);
my $FileData = ${$self->GetFileData($FilePath)};
my $ProductHash = {};
my #LineData = split("\n", $FileData);
foreach my $LineData (#LineData){
next if($LineData eq '' || $LineData =~ /^#/);
my #DataArray = split("\t", $LineData, 3);
my $ProductId = $DataArray[0];
my $ProductName = $DataArray[1];
my $ProductTop = $DataArray[2];
$ProductHash->{$ProductId} = {
'id' => $ProductId,
'name' => $ProductName,
'top' => $ProductTop,
};
}
return $ProductHash;
}
sub SetTemplateParameter{
my $self = shift;
my $TemplateData = shift;
my $ProductData = shift;
$TemplateData = ${$TemplateData} if(ref($TemplateData) eq 'SCALAR');
$TemplateData =~ s/\$\{(.*?)\}/$ProductData->{$1}/ges;
return \$TemplateData;
}
sub GetFileData{
my $self = shift;
my $FilePath = shift;
my $FileData = '';
if(-e "${FilePath}"){
my $FileHandle = new FileHandle;
sysopen($FileHandle, "${FilePath}", O_RDONLY);
$FileData = join'',<$FileHandle>;
close($FileHandle);
}
return \$FileData;
}
1;
cgi file: product_random_list.cgi
#!/usr/bin/perl
use FindBin;
use lib "$FindBin::Bin/lib";
use strict;
use CGI;
use ProductLib;
use Data::Dumper;
my $ProductFormat = ' <a class="card">
<div class="card-body">
<strong>${name}</strong>
</div>
</a>';
my $q = new CGI;
my $ProductLib = new ProductLib();
my $TargetMode = $q->param('mode') || 'init';
my $TargetTop = $q->param('top');
my $ProductList = {};
if($TargetMode eq 'init'){
$ProductList = $ProductLib->SearchRandomProduct($TargetTop);
}
my $ProductHtml = '';
foreach my $ProductId (
sort {
$ProductList->{$a}->{'id'} cmp $ProductList->{$b}->{'id'}
}
(keys %{$ProductList})){
my $ProductData = $ProductList->{$ProductId};
$ProductHtml .= ${$ProductLib->SetTemplateParameter(\$ProductFormat, $ProductData)};
}
print "Content-Type: text/plain; charset=utf8\n\n";
print $ProductHtml;
exit;
index file : index.html
<!DOCTYPE html>
<html>
<body>
<section>
<div class="container-fluid">
<div class="card-deck sMb">
<!--#include virtual="/ssi/product_random_list.cgi?top=top" -->
</div>
</div>
</section>
</body>
</html>
please help me to display them randomly by three top data when reload page in above index page...
display them randomly by three top data when reload page.
You can select three random items from the product list by using for example List::Util::shuffle(). Example:
use strict;
use warnings;
use List::Util qw(shuffle);
my $ProductList = {
id01 => {id => 'id01', name => 'name01', top => 'top'},
id10 => {id => 'id10', name => 'name10', top => 'top'},
id04 => {id => 'id04', name => 'name04', top => 'top'},
id07 => {id => 'id07', name => 'name07', top => 'top'},
id05 => {id => 'id05', name => 'name05', top => 'top'},
};
my #ids = keys %$ProductList;
my #idx = shuffle 0..$#ids;
my #randidx = #ids[#idx[0..2]];
Every time reload page show different 3 data from top data
In order to recognize if the page is reloaded or not, you could use a session variable. See CGI::Session for more information.
I'm trying to make an update with values from a form and pass it into an update controller using a route, there's no error given but why there's nothing happen after I updated the data?
Form:
<form action="/update" id="frm_edit" method="post" enctype="multipart/form-data">
Routes:
Route::post('/update', 'EditManga#update'); //update route
Route::post('/admin_page/manga_list', 'Add_Manga_Controller#upload')->name('upload.image');
Route::get('/admin_page/manga_list','ShowData#Manga_list');
Controller:
public function update(Request $request){
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
$judul = $request->input('jdmanga');
$alternatif = $request->input('almanga');
$author = $request->input('aumanga');
$status = $request->status;
$lastup = $request->input('lumanga');
$genre = $request->input('grmanga');
$lastc = $request->input('lcmanga');
$sinopsis = $request->input('sinopsis');
$file = $request->file('image');
DB::table('add_manga')->where('kode_manga',$kode_manga)->update([
'judul_manga' => $judul,
'alt_title' => $alternatif,
'author' => $author,
'status' => $status,
'uploaded' => $lastup,
'genre' => $genre,
'latest' => $lastc,
'summary' => $sinopsis
]);
return redirect('/admin_page/manga_list');
}
}
is there any other way or there something's wrong with my code?, Thank you.
In you scenario this another of doing this:
public function update(Request $request, $id)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
//getting the target row to updae
$addmanga = DB::table('add_manga')->select('*')
->where('kode_manga',$kode_manga)->get();
$id = $addmanga->id; // getting the id of the target
$add_manga = App\YOUR_MODEL_NAME::find($id);
$add_manga->judul_manga = $request->input('jdmanga');
$add_manga->alt_title = $request->input('almanga');
$add_manga->author = $request->input('aumanga');
$add_manga->status = $request->status;
$add_manga->uploaded = $request->input('lumanga');
$add_manga->genre = $request->input('grmanga');
$add_manga->latest = $request->input('lcmanga');
$add_manga->summary = $request->input('sinopsis');
$add_manga->file = $request->file('image');
$add_manga->save();
return redirect('/admin_page/manga_list');
}
Hope this will work for you!
I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS
Using Laravel5.1 ...
I'm trying to convert this JSON:
"[{"John Doe":"john.gmail.com"},{"Frank Smith":"frank#frank.com"},{"Jie Brent":"jie#gmail.com"},{"Jeffrey Manney":"jeff17#gmail.com"}]"
To this:
"[{"name":"John Doe", "email":"john.gmail.com"},{"name":"Frank Smith", "email":"frank#frank.com"},{"name":"Jie Brent", "email":"jie#gmail.com"},{"name":"Jeffrey Manney", "email":"jeff17#gmail.com"}]"
This is my code:
$users_storage = [];
foreach($rcf_and_rcfm_users as $key => $user){
$users_storage[][$key] = $user;
}
$users = json_encode($users_storage);
dd($users);
The $rcf_and_rcfm_users variable is a collection of users from the database.
If I understand it correctly.
$users_storage = [];
foreach($rcf_and_rcfm_users as $name => $email){
$users_storage[] = [
'name' => $name,
'email' => $email,
];
}
$users = json_encode($users_storage);
dd($users);
I think this is what you're trying to accomplish.