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.
Related
The problem I am facing in the api is as follows: it is not accepting array of multiple arrays:
...
"message": "Array to string conversion",
"exception": "ErrorException",
"file": "/home/deepan8/pich.abc.com/vendor/laravel/framework/src/Illuminate/Support/Str.php",
"line": 762,
"trace": [
{
"file": "/home/deepan8/pich.abc.com/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php",
"line": 257,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},]
My code snippet looks like this:
$voucherArray = [];
foreach($users as $user) {
$voucherArray[] = ['voucher_code' => rand(10000, 999999),
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active",
];
}
$ids = DB::table('pich_voucher')->insertGetId($voucherArray);
foreach($ids as $id) {
}
I need to add all the rows at once instead of adding them one by one to improve performance.
Does Laravel have some function which can provide this facility or any SQL Query where we can add multiple rows and extract their ids at the same time?
You can insert multiple rows using insertGetId() method. If you want really want to insert multiple rows and get the IDs, just use looping.
example:
$ids = [];
foreach ($users as $user) {
$voucherArray = array(
'voucher_code' => rand(10000, 999999),
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active"
);
$ids[] = DB::table('pich_voucher')->insertGetId($voucherArray);
}
Or another way use insert method but not get the ids. if you want to get the ids you could use like below:
$voucherArray = [];
$codes = [];
foreach ($users as $user) {
$code= rand(10000, 999999);
$codes[] = $code;
$voucherArray[] = array(
'voucher_code' => $code,
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active"
);
}
DB::table('pich_voucher')->insert($voucherArray);
$ids = DB::table('pich_voucher')->whereIn('voucher_code', $codes)->pluck('id')->toArray();
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'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
I am struggling to get the "merchant" -> "id" from the Groupon API below, while I don't have any problems to return the discountPercent.
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $results) {
$discountPercent = $results['options'][0]['discountPercent'];
$merchantId = $results['merchant'][0]->id;
echo $discountPercent.'<br>';
echo $merchantId;
}
?>
If someone could point me to the right direction.
Many Thanks,
Ok here is the answer:
$merchantId = $results['merchant']['id'];
>>>This may be the Reason.....
>>>Explanation for:: $results['options'][0]['discountPercent']
In $json array you can see
[options] => Array
(
[0] => Array
(
.........
[discountPercent] => 54
.........
)
)
Here, the hierechy is
option->0(key)->discountPercent
that's why you need to use index '0';
>>>Explanation for::: $results['merchant'][0]->id
in json array you can see
[merchant] => Array
(
[id] => global-cuisine-restaurant
[uuid] => 183dd76b-a1a6-40cf-93c7-33e00f379451
[name] => Global Cuisine Restaurant
[websiteUrl] => http://www.globalcuisine.ie/
[twitterUrl] =>
[facebookUrl] =>
[ratings] =>
)
Here the hirerchy is:::
merchant->id (notice '0' is not present as any subarray index)
that's why should use
$merchantId = $results['merchant']['id'];
finally use can use code::
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $key=>$results) {
$discountPercent = $results['options'][0]['discountPercent'];
$discountPercent[] = $results['options'][0]['discountPercent'];//to get all in one;
$merchantId = $results['merchant']['id'];
$merchantId[] = $results['merchant']['id'];//to get all in one
echo $discountPercent.'<br>';
echo $merchantId;
}
?>
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);
}