array data insert in laravel - php

I am getting this kind of data from the database in array form.
Illuminate\Support\Collection {#1434
#items: array:4 [
0 => 20
1 => 21
2 => 22
3 => 19
]
}
I want to insert the this array data through the controller For each array element.
foreach($plucked as $data){
$attendant_data = new EmployeeAttendant();
$attendant_data->user_id = $data;
$attendant_data->date = Carbon::now()->format('Y-m-d');
$attendant_data->time = Carbon::now()->format('H:i:s');
$attendant_data->present = '0';
$attendant_data->save();
}
Data is being inserted only for the first array element.

Just prepare the data and insert it.
$insertableAttendant = [];
foreach($plucked as $data){
$attendant_data = [];
$attendant_data['user_id'] = $data;
$attendant_data['date'] = Carbon::now()->format('Y-m-d');
$attendant_data['time'] = Carbon::now()->format('H:i:s');
$attendant_data['present'] = '0';
$insertableAttendant[] = $attendant_data;
}
EmployeeAttendant::insert($insertableAttendant);

Related

Sort an associative/multidimensional array based on a sub-object array value

I'm looking to sort an associative array ($rows) based on a sub-object array value. The array consists of products, and some of them has a "badge". These can be a campaign badge, and I would like to sort them, so they are displayed first.
I've searched, but couldn't find a solution I could use. This is beyond my skill level.
In pseudocode I'm looking to do the following:
IF $row->badges is array // product has a badge
AND $row->badges[$i]->badge_name == 'campaign' // product has the right badge
THEN sort array so all campaign products are displayed first, ordered by product_name
Example of my array:
Array (
[0] => stdClass Object
(
[product_id] => 195
[product_name] => Product name
[badges] => Array
(
[0] => stdClass Object
(
[badge_id] => 3
[badge_name] => NAME TO SORT ON
[badge_published] => 1
[badge_access] => all
)
)
)
[1] = ...
[2] = ...
[3] = ...
According to your logic, we need to sort the array by badge condition and within the campaign badge group we need to sort by a product name. Please take a look at the following snippet.
<?php
declare(strict_types=1);
$campaignBadge = new \stdClass();
$campaignBadge->badge_id = 3;
$campaignBadge->badge_name = 'campaign';
$campaignBadge->badge_published = 1;
$campaignBadge->badge_access = 'all';
$whateverBadge = new \stdClass();
$whateverBadge->badge_id = 5;
$whateverBadge->badge_name = 'whatever';
$whateverBadge->badge_published = 1;
$whateverBadge->badge_access = 'all';
$product1 = new \stdClass();
$product1->product_id = 195;
$product1->product_name = 'Product name 1';
$product1->badges = [
$campaignBadge,
];
$product2 = new \stdClass();
$product2->product_id = 290;
$product2->product_name = 'Amazing product';
$product2->badges = [
$whateverBadge,
];
$product3 = new \stdClass();
$product3->product_id = 102;
$product3->product_name = 'Some product';
$product3->badges = [
$whateverBadge,
];
$product4 = new \stdClass();
$product4->product_id = 250;
$product4->product_name = 'Awesome product';
$product4->badges = [
$campaignBadge,
];
$products = [
$product1,
$product2,
$product3,
$product4,
];
usort($products, static function ($a, $b) {
$aHasCampaignBadge = false;
foreach ($a->badges as $badge) {
if ('campaign' === $badge->badge_name) {
$aHasCampaignBadge = true;
break;
}
}
$bHasCampaignBadge = false;
foreach ($b->badges as $badge) {
if ('campaign' === $badge->badge_name) {
$bHasCampaignBadge = true;
break;
}
}
if (!$aHasCampaignBadge && !$bHasCampaignBadge) {
return 0;
}
if ($aHasCampaignBadge && $bHasCampaignBadge) {
return strcmp($a->product_name, $b->product_name);
}
return $aHasCampaignBadge < $bHasCampaignBadge;
});
var_dump($products);

Get data from multiple array in Controller

I have country list in array with multiple array, like:
public static function listCountries()
{
$this->country = array(
array(1, 'SAD', 'sad.png'),
array(2, 'Argentina', 'argentina.png'),
array(3, 'Australija', 'australija.png'),
array(4, 'Novi Zenland', 'noviz.png'),
array(5, 'Belgija', 'belg.png'),
array(6, 'Nizozemska', 'nizozemska.png')
);
}
But when i do foreach for array, i'm getting this:
//From DB
$item->country = "1,4";
$item->country = explode(",", $item->country);
for($i=0; $i < count($item->country); $i++) {
$index = $item->country[$i];
if( !empty($this->country[$index]) ) {
$item->country[$i] = $this->country[$index];
}
}
$item->country = implode(",", $item->country);
echo $item->country;
But i'm getting something like this:
array:2 [▼
0 => array:3 [▼
0 => 5
1 => "Belgija"
2 => "belg.png"
]
1 => array:3 [▼
0 => 2
1 => "Argentina"
2 => "argentina.png"
]
]
1 = SAD, 4 = Novi Zenland, not Belgija and Argentina
There is no good country, also no data what i want. How to fix this?
You can use this foreach loop to go through the other array and swap the string if the number matches:
$item->country = "1,4";
$item->country = explode(",", $item->country);
for($i=0; $i < count($item->country); $i++) {
$index = $item->country[$i];
foreach($this->country as $c) {
if($c[0] == $index) {
$item->country[$i] = $c[1]; // or $item->country[$i] = $c; if you want all three items
break;
}
}
}
$item->country = implode(",", $item->country);
echo $item->country;
// Should output: SAD,Novi Zenland
The indexes in arrays are 0-based, which means that:
$index = $item->country[$i];
Has to become
$index = $item->country[$i - 1];
To correlate with the country ids. Otherwise, it is always one off. This is assuming that the ids are always ordered from least to greatest, and all ids are a continuous range.

PHP Permutations with exception of similar sequence

My permutation/combinations of data
$combinations = [[]];
$data = [
['alteration1', 'alteration2', 'alteration3', 'alteration4' ... upto 5 each],
['alteration1', 'alteration5', 'alteration6', 'alteration7' ... upto 5 each],
['alteration8', 'alteration9', 'alteration10', 'alteration5' ... upto 5 each],
... upto 6 max
];
$length = count($data);
for ($count = 0; $count < $length; $count++) {
$tmp = [];
foreach ($combinations as $v1) {
foreach ($data[$count] as $v2)
$tmp[] = array_merge($v1, [$v2]);
}
$combinations = $tmp;
}
print_r($combinations);
The script would generate such sets
0 => array:3 [▼
0 => "alteration1"
1 => "alteration1"
2 => "alteration8"
]
1 => array:3 [▼
0 => "alteration1"
1 => "alteration1"
2 => "alteration9"
]
... the issue begins when I start getting the same sequences of data in my case array index 0 and 20 would be exactly the same despite any position.
20 => array:3 [▼
0 => "alteration8"
1 => "alteration1"
2 => "alteration1"
]
21 => array:3 [▼
0 => "alteration1"
1 => "alteration9"
2 => "alteration1"
]
$final = []; // remove duplicates
The basic idea is to keep $combinations array's unique (alteration1,alteration2,alteration3) is equal to (alteration3,alteration1,alteration2) therfore it should be skipped in the $final array. I haven't really found anything around SO and google. Thanks for the help. $data dimentions [ from 1 - 6 ], each array inside can be [ 1 - 6 ]. Following script might not be working as expected .
http://sandbox.onlinephpfunctions.com/code/3ad5084386c2185f7619aaac152b638873039ee8
We iterate over the data and find unique elements first for each set using array_unique.
We then natsort them to get a sorted form and serialize them using implode(). By doing this, we would get the same serialized code for sets ABC,CBA,BAC etc.
We then find duplicates using keys check inside a variable, say $set. If the serialized key is set, we exclude it from the results, else we include it in our final results.
Snippet:
<?php
$data = [
['alteration1', 'alteration4',],
['alteration2','alteration3'],
['alteration2','alteration3'],
[]
];
$combinations = [[]];
foreach($data as $index => $current_data){
$current_data = array_unique($current_data);
if(empty($current_data)) continue;
$temp_combinations = [];
foreach($current_data as $value){
foreach($combinations as $each_combination){
$temp_combinations[] = array_merge($each_combination,[$value]);
}
}
$combinations = $temp_combinations;
}
$set = [];
$unique_combinations = [];
foreach($combinations as $each_combination){
natsort($each_combination);
$serialized_form = implode(",",$each_combination);
if(isset($set[$serialized_form])) continue;
if(empty($each_combination)) continue;
$unique_combinations[] = $each_combination;
$set[$serialized_form] = true;
}
print_r($unique_combinations);
Demo: https://3v4l.org/Do6oH

How to save it in database

In my database i have column like id,product_id,company_name,service,qty,delivery_cost,delivery_date,order_status etc.
I view i used Jquery and Html and jquery dynamically add more input fields of product_id,service,delivery_cost,qty,delivery_date,order_status on clicking ADD more button.On submiting form i got this in controller on doing dd($allData);
My question is how can i save this data in database
array:8 [▼
"_token" => "gSddIeA11OBV60xU9YiDXn8fmsfkwxlQ85QmDdkQ"
"service" => array:3 [▼
0 => "cement"
1 => "iron"
2 => "steel"
]
"qty" => array:3 [▼
0 => "5"
1 => "44"
2 => "5"
]
"delivery_cost" => array:3 [▼
0 => "5465"
1 => "553"
2 => "554"
]
"delivery_date" => array:3 [▼
0 => "2016-12-16"
1 => "2016-12-08"
2 => "2016-12-17"
]
"order_status" => "Confirm"
"delivery_vehicle" => array:1 [▼
0 => "Self_elivery"
1 => "Self_elivery"
2 => "Self_elivery"
]
]
public function store(Request $request)
{
$allData= $request->all();
dd($allData);
$product = new Order;
}
i try this
public function store(Request $request)
{
$date = $request->get('delivery_date');
$cost = $request->get('delivery_cost');
$service = $request->get('service');//add quotes next to service
foreach($date as $deliveryDate)
{
foreach($cost as $proAmount){
$db = new Order;
$db->delivery_date = $deliveryDate;
$db->amount = $proAmount;
$db->save();
}
}
return"ok";
}
I tried this way but it store same data multiple times may be because of loop inside of loop.I need your help to store this data in database
Using for() should work for you:
$data = $request->all();
for ($i = 0; $i < count($data['delivery_date']); $i++) {
$db = new Order;
$db->delivery_date = $data['delivery_date'][$i];
$db->delivery_cost = $data['delivery_cost'][$i];
....
$db->save();
}
You can try this If you want to use foreach $key will give you the index.
$date = $request->get('delivery_date');
$cost = $request->get('delivery_cost');
$service = $request->get('service');
foreach($date as $key=>$deliveryDate)
{
$db = new Order;
$db->delivery_date = $deliveryDate;
$db->amount = $cost[$key];
$db->save();
}
return"ok";
Hope this help you. Ask if any query
Do bulk insert instead of running new sql query for every insert(if all the request params exist in single table).
$data = [];
foreach ($request->all() as $param => $val) {
if( is_array($val) ) // Ignore string params. i.e. _token, order_status
{
foreach ($val as $key => $value) {
$data[$index][$param] = $value;
$data[$index]['created_at'] = \Carbon\Carbon::now();
$data[$index]['updated_at'] = \Carbon\Carbon::now();
$index++;
}
$index = 0;
}
}
Model::insert($data);
Using foreach() should work for you very easy:
$inputdata = $request->all();
foreach ($inputdata as $key=>$val) {
$dbdata = new Order;
$dbdata ->delivery_date = $data['delivery_date'][$key];
$dbdata ->delivery_cost = $data['delivery_cost'][$key];
....
$dbdata ->save();
}

PHP: how to process this data from database

I'm pretty new to programming so I'm sorry if this is very nooby.
In a dummy database I have a column called currencies. The column has this data:
36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN
Above data is the amount and its respective currency the user has paid.
What I want to do is to display a table with each currency and the total amount of sales for that country and also display it in table form.
So with the above data, I want the output below:
Currency | # Sales
____________________
USD 4
GPB 2
BGN 2
____________________
Total: 8
Try this
$data = "36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN";
$data = explode(",", $data);
$result = array();
foreach ($data as $value) {
$d_array = explode(":", $value);
if(isset($result[$d_array[1]]))
$result[$d_array[1]] +=1;
else
$result[$d_array[1]] = 1;
}
$total = count($data);
var_dump($result);
var_dump($total);
And the result
array (size=3)
'USD' => int 4
'GBP' => int 2
'BGN' => int 2
int 8
$data = "36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN";
$data = explode(",", $data);
$final_array = array();
foreach ($data as $value)
{
$new_array = explode(":", $value);
array_push($final_array, $new_array[1]);
}
$final_array = array_count_values($final_array);
print_r($final_array);
Result
Array ( [USD] => 4 [GBP] => 2 [BGN] => 2 )
Take a look at my example. I hope its fine for you.
$orders = array("36:USD","74:GBP","68:USD","119:USD","114:BGN","15:USD","32:GBP","1:BGN");
$totalData = array();
foreach($orders as $singleOrder) {
$explodedData = explode(':',$singleOrder);
if(!isset($totalData[$explodedData[1]])) {
$totalData[$explodedData[1]] = $explodedData[0];
} else {
$totalData[$explodedData[1]] += $explodedData[0];
}
}
var_dump($totalData);
result
array (size=3)
'USD' => int 238
'GBP' => int 106
'BGN' => int 115

Categories