how to convert array from postgres db to array variable in laravel? - json

how to convert array from postgres db to array variable in laravel ?
my postgres array structure
i have result var_dump from laravel :
0 => array:1 [
"order_itemset" => "{8,11}"
]
1 => array:1 [
"order_itemset" => "{8,12}"
]
2 => array:1 [
"order_itemset" => "{17,10}"
]
]
how i can get the data and store the data to array variable?
like this
$data = [['8', '11'], ['8', '12'], ['17', '10']];
sorry for my broken english ,thanks.

Take a look here.
You can simplify this code if your postgres query returns an array "[8,11]" instead of a "sort-of" JSON "{8,11}"
<?php
$values = array_column($your_data, 'order_itemset');
$values = array_map(function ($v) {
preg_match("/^\{(.+)\}$/", $v, $matches);
if ($matches[1]) {
return explode(',', $matches[1]);
}
return null;
}, $values);
print_r($values);

you can use foreach
$original_array = $your_array; //Your base array that you showed us on your Question
$base_array = array();
foreach($original_array as $original)
{
$child_array = array();
foreach($original->order_itemset as $a)
{
$child_array[] = $a;
}
$base_array[] = $child_array;
unset($child_array);
}
die($base_array);

Related

Need to insert array data using laravel controller

i have a array data like this below. i want to save some of it's data not all into mysql table.
when i dd($request->all) data in my controller function it looks like this.
array:1 [
"{"cart":" => array:1 [
"{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}" => null
]
]
i want to add id and total quantity shows last object into a table. table rows looks like this.
$table->increments('id');
$table->integer('order_id');
$table->integer('product_id')->unsigned();
$table->integer('total_quantity');
$table->timestamps();
$table->softDeletes();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
how can i write a store function using this data in laravel
result data looks like this
Array
(
[{"cart":] => Array
(
[{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}] =>
)
)
this is my latest update
$data = [];
foreach ($request->all() as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
dd($value);
}
Loop through your data coming and make array as below i have shown.
Try this one by creating the array of the data and insert array to the database as bulk data:
// this will decode your json data that you're getting in the post data
$postdata = json_decode($request->all(), true);
$data = [];
foreach ($postdata as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
}
// $data now will have data as following structure
$data = [[
'product_id' => 2,
'total_quantity' => 7
],
[
'product_id' => 2,
'total_quantity' => 7
]];
$order = Order::create($data);

How can I create a json file from object with serializer?

This is my object $input:
$input = $this->em->getRepository(Data::class)->findAll();
foreach($input as &$arr){
$arr->{"Sunshine"} = 'Clouds';
}
The output of $input:
Data {#1523 ▼
-id: 23
-name: "cat"
-timestamp: DateTime #1570445917 {#1517 ▶}
+"Sunshine": "Clouds"
}
I am using serializer to create a JSON file $data
// Serialize your object in JSON
$context = [
'circular_reference_handler' => function ($object) {
return $object->getId();
},
'circular_reference_limit' => 0,
];
$data = $serializer->serialize($input, 'json', $context);
$data:
"[{"id":21,"name":"cat","timestamp":"07.10.2019"}] ◀"
I wonder, why "Sunshine" is not in the JSON file. Does it have something to do with the +? What does + mean?
I think you're assigning the key incorrectly. A key should be assigned like this:
$arr['keyName'] = $value
You're assigning it like this:
$arr->{"keyName"} = $value
I hope I helped you with this answer!

Api Response and Json laravel format

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

Add key to multiple list of JSON

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.

How to create associative array in Yii2 and convert to JSON?

I am using a calendar in my project and I want to pass data from my Event model to view file in JSON format. I tried following but it didn't work and am not able to display the data properly
$events = Event::find()->where(1)->all();
$data = [];
foreach ($events AS $model){
//Testing
$data['title'] = $time->title;
$data['date'] = $model->start_date;
$data['description'] = $time->description;
}
\Yii::$app->response->format = 'json';
echo \yii\helpers\Json::encode($data);
But it only returns one model in that $data array, the final data should be in following format:
[
{"date": "2013-03-19 17:30:00", "type": "meeting", "title": "Test Last Year" },
{ "date": "2013-03-23 17:30:00", "type": "meeting", "title": "Test Next Year" }
]
When you write this:
\Yii::$app->response->format = 'json';
before rendering data, there is no need to do any additional manipulations for converting array to JSON.
You just need to return (not echo) an array:
return $data;
An array will be automatically transformed to JSON.
Also it's better to use yii\web\Response::FORMAT_JSON constant instead of hardcoded string.
Another way of handling that will be using ContentNegotiator filter which has more options, allows setting of multiple actions, etc. Example for controller:
use yii\web\Response;
...
/**
* #inheritdoc
*/
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index'], // in a controller
// if in a module, use the following IDs for user actions
// 'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}
It can also be configured for whole application.
Update: If you are using it outside of controller, don't set response format. Using Json helper with encode() method should be enough. But there is also one error in your code, you should create new array element like this:
$data = [];
foreach ($events as $model) {
$data[] = [
'title' => $time->title,
'date' => $model->start_date,
'description' => $time->description,
];
}
You can try like this:
$events = Event::find()->select('title,date,description')->where(1)->all()
yii::$app->response->format = yii\web\Response::FORMAT_JSON; // Change response format on the fly
return $events; // return events it will automatically be converted in JSON because of the response format.
Btw you are overwriting $data variable in foreach loop you should do:
$data = [];
foreach ($events AS $model){
//Make a multidimensional array
$data[] = ['time' => $time->title,'date' => $model->start_date,'description' => $time->description];
}
echo \yii\helpers\Json::encode($data);