Laravel How to Make Array into a Collection? - arrays

Good day everyone, I have this function that can generate time interval and store them to $time.
if(strtotime($startTime) <= strtotime($endTime))
{
$this->time[$i]['room'] = '49';
$this->time[$i]['day'] = 'T-Th';
$this->time[$i]['c_time'] = $start.'-'.$end;
$this->time[$i]['sy'] = '2021-2022';
$this->time[$i]['sem'] = '1st';
}
Sample output of $time is like this
1 => array:5 [▼
"room" => "49"
"day" => "T-Th"
"c_time" => "07:00-08:30"
"sy" => "2021-2022"
"sem" => "1st"
]
2 => array:5 [▼
"room" => "49"
"day" => "T-Th"
"c_time" => "08:30-10:00"
"sy" => "2021-2022"
"sem" => "1st"
]
3 => array:5 [▼
"room" => "49"
"day" => "T-Th"
"c_time" => "10:00-11:30"
"sy" => "2021-2022"
"sem" => "1st"
]]
What should I do so that the output would be a collection->toArray() just like this
array:5 [▼
0 => {#1416 ▼
+"room": "49"
+"day": "M-W"
+"c_time": "13:00-14:00"
+"sy": "2021-2022"
+"sem": "1st"
}
1 => {#1435 ▼
+"room": "49"
+"day": "M-W"
+"c_time": "11:30-13:00"
+"sy": "2021-2022"
+"sem": "1st"
}
2 => {#1433 ▼
+"room": "49"
+"day": "M-W"
+"c_time": "13:00-14:30"
+"sy": "2021-2022"
+"sem": "1st"
}]

Since you did not provide us with where you define the $time variable, I can't help you with any issues there. However, first, instantiate that variable as a collection.
$this->time = collect([]);
And then you can push in the following manner.
$this->time->put($i, (object) [
'room' => '49',
'day' => 'T-Th',
'c_time' => $start.'-'.$end,
'sy' => '2021-2022',
'sem' => '1st',
]);

The simplest way to convert an array to collection is to use Laravel's collect() helper function. It takes an array as a parameter and returns a collection type.
For example if we have this array:
$a = [
['name' => "abc", 'age' =>45],
['name' => "xyz", 'age' =>20],
];
dd(collect($a));
The output will be:

Related

how to perform calculations for each record in collection

i have an collection of bets, where i need to calculate var $profit.
Each record has stake and odds.
Here is my collection:
Illuminate\Database\Eloquent\Collection {#1900 ▼
#items: array:4 [▼
0 => App\Models\Bet {#1912 ▶}
1 => App\Models\Bet {#1906 ▶}
2 => App\Models\Bet {#1857 ▶}
3 => App\Models\Bet {#1882 ▶}
]
}
and attributes of array:
#attributes: array:19 [▼
"id" => 4
"user_id" => 1
"status_id" => 1
"content" => "some text"
"sport" => "Basketball"
"competition" => "Premier league"
"start_date" => "2021-12-08"
"bookmaker_id" => 1
"team1" => "team one"
"team2" => "team two"
"selection_id" => 1
"tip" => "2,5"
"odds" => "5"
"unit_id" => 5
"created_at" => "2021-12-06 13:32:46"
"updated_at" => "2021-12-06 13:32:46"
"created_by" => 1
"updated_by" => null
"deleted_by" => null
]
how can i make calculations in each collection array?
for exmpl to count profit (odds*unit_id(stake))
this was the thing i needed:
$bets = array_map(function($item) {
$item['won'] = number_format((double)$item['odds'] * (int)$item['unit_id'],3);
return $item;
}, $bets);

Check data structure and disregard if hash or array

I have a bunch of Hashes inside of an array. When checking my keys and values I get the expected output except for some special cases as they refer to more Arrays/Hashes.
Think of something like this:
#AoH = ( { 'husband' => "homer", 'wife' => "marge" },
{ 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
{ 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} });
My function iterates through the array and displays my keys and values as in the following:
sub function(...){
print "$key => $value\n";
}
husband => homer
wife => marge
people => ARRAY(0x6b0d80)
Bob => 24
Lukas => 37
vegetables => HASH(0x2570d38)
tomato => red
carrot => orange
Now I want to access my keys and values, but when getting something like ARRAY or HASH as value, I want to disregard that hash and not print it.
Is there some kind of way to only access Values with type scalar?
So far I tried this:
if ($value eq 'ARRAY') {
}
elsif ($value eq ref {}) {
}
else {
print "$key => $value\n";
}
But, it ends up printing exactly the same as above and does not disregard the other data structures.
For an arbitrary data structure like yours, you can use Data::Traverse:
use warnings;
use strict;
use Data::Traverse qw(traverse);
my #AoH = ( { 'husband' => "homer", 'wife' => "marge" },
{ 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
{ 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} });
traverse { print "$a => $b\n" if /HASH/ } \#AoH;
Output:
wife => marge
husband => homer
Bob => 24
Lukas => 37
carrot => orange
tomato => red
Following demo code does not utilize external modules, provided for educational purpose.
use strict;
use warnings;
use feature 'say';
my #AoH = ( { 'husband' => "homer", 'wife' => "marge" },
{ 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
{ 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} });
drill_in( \#AoH );
sub drill_in {
my $data = shift;
if( ref $data eq 'ARRAY' ) {
drill_in($_) for #$data;
} elsif ( ref $data eq 'HASH' ) {
while( my($k, $v ) = each %{$data} ) {
(ref $v eq 'ARRAY' or ref $v eq 'HASH') ? drill_in($v) : say "$k => $v";
}
}
}
Output
husband => homer
wife => marge
Lukas => 37
Bob => 24
tomato => red
carrot => orange

How to join a array and MySQL table in Laravel

i have an array like
array:5 [▼
188 => array:17 [▼
"user_id" => "176"
"product_id" => "188"
"qty" => "2"
"date" => "03-05-2020"
"product_type" => "rear type"
"custom_color_title" => ""
"custom_color_price" => ""
"bolt_title" => ""
"bolt_price" => ""
"hub_center_rings_title" => ""
"hub_center_rings_price" => ""
"wheel_spacers_title" => ""
"wheel_spacers_price" => ""
"tire_pressure_title" => ""
"tire_pressure_price" => ""
"product_price" => 1890
"product_size" => ""
]
176 => array:17 [▼
"user_id" => ""
"product_id" => "176"
"qty" => "2"
"date" => "03-05-2020"
"product_type" => "wheel type"
"custom_color_title" => ""
"custom_color_price" => ""
"bolt_title" => ""
"bolt_price" => ""
"hub_center_rings_title" => ""
"hub_center_rings_price" => ""
"wheel_spacers_title" => ""
"wheel_spacers_price" => ""
"tire_pressure_title" => ""
"tire_pressure_price" => ""
"product_price" => 1680
"product_size" => ""
]
224 => array:17 [▶]
]
from a session variable this array
and mysql table fields are id,name,img etc.. how to join the array.product_id and table.id ,
my query like $table=DB::select('SELECT * FROM products');i am doing in laravel any way to join mysql table and array?
Your mysql dump which you want to join is missing. But i think i understand you want:
foreach($sessionArray as $sessionArrayKey => $sessionArrayVal)
{
$findInDb = array_search($sessionArrayVal['product_id'], array_column($dbArray, 'id'));
if ($findInDb)
{
$sessionArray[$sessionArrayKey] = array_merge($sessionArray[$sessionArrayKey],$dbArray[$findInDb])
}
}

How to merge array from different array

Hi i have problem with merge array,
How to merge array from different array
From Here
Array 1
array:6 [
"patient_name" => "Pasien 4"
"employee_no" => "1114"
"birth_date" => "1990-05-02"
"gender" => "L"
"department_code" => "D0004"
"section_code" => "S0004"
]
Array 2
array:2 [
"kd_layan" => "10000104 "
"nama_layan" => "PAKET MCU ADVANCE (MALE)"
]
To Here
array:8 [
"patient_name" => "Pasien 4"
"employee_no" => "1114"
"birth_date" => "1990-05-02"
"gender" => "L"
"department_code" => "D0004"
"section_code" => "S0004"
"kd_layan" => "10000104 "
"nama_layan" => "PAKET MCU ADVANCE (MALE)"
]
Any solution for this problem?
Thanks
It has very simple solution using array_merge() function of php.
array_merge() function merges one or more arrays into one array.
You can assign one array to the function, or as many as you like.
If two or more array elements have the same key, the last one overrides the others.
in your case use it as below
$arr1=[
"patient_name" => "Pasien 4",
"employee_no" => "1114",
"birth_date" => "1990-05-02",
"gender" => "L",
"department_code" => "D0004",
"section_code" => "S0004"
];
$arr2=[
"kd_layan" => "10000104 ",
"nama_layan" => "PAKET MCU ADVANCE (MALE)"
];
print_r(array_merge($arr1,$arr2));
for more see documentation
use array_merge to merge two array
$array1 = [
"patient_name" => "Pasien 4",
"employee_no" => "1114",
"birth_date" => "1990-05-02",
"gender" => "L",
"department_code" => "D0004",
"section_code" => "S0004",
];
$array2 = [
"kd_layan" => "10000104",
"nama_layan" => "PAKET MCU ADVANCE (MALE)"
];
$res = array_merge($array1, $array2);
echo '<pre>';
print_r($res);
check demo code
Use array_merge()
It merges one or more arrays into one array.
Syntax : array_merge(array1, array2, array3, ...)
use array_merge
$arr1 = [
"patient_name" => "Pasien 4"
"employee_no" => "1114"
"birth_date" => "1990-05-02"
"gender" => "L"
"department_code" => "D0004"
"section_code" => "S0004"
]
arr2 = [
"kd_layan" => "10000104 "
"nama_layan" => "PAKET MCU ADVANCE (MALE)"
]
$result = array_merge($arr1, $arr2);
echo '<pre>';
print_r($result);
Below i have mention an example which will merge two array and the output will be as it is as you want.
$a = array('1' => 'one','2' => 'two');
$b = array('3' => 'three','4' => 'four');
$c = ($a + $b);
print_r($c);

foreach inside foreach and out put first foreach in array

Assume I have an array called (data) and inside my array I have a foreach on products. I need to get each of these product packages inside this (data) array.
Here is what I've tried:
foreach ( $products as $product ) {
$data[] = [
'id' => $product->id,
'packages' => [],
]
foreach ( $product->packageId as $package ) {
$data[]['packages'] = [
'package_id' => $package['id'],
];
}
}
This returns:
- 0 [
id: 977
packages: []
]
- 1 [
packages
package_id: 14
]
- 2 [
packages
package_id: 15
]
I need to return something like this:
- 0 [
id: 977
packages: [
package_id: 14,
package_id: 15
]
]
Update
as #Helioarch and #albus_severus mentioned in they answers that I should create the package array first then include that into the data array
this solution will add the old array of packages in every time the products loops
For Example
product 1 has packages [1,2,3]
product 2 has packages [4,5,6]
in this my case here it will become
product 1 have packages [1,2,3]
product 2 will have packages [1,2,3,4,5,6] <- witch is wrong.
Update 2
Here is my full code
foreach ( $products as $product ) {
$sums = 0;
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
You should create the package array first then include that into the data array like so:
foreach ( $products as $product ) {
$packages = [];
foreach ( $product->packageId as $package ) {
$packages[] = [
'package_id' => $package['id'],
];
}
$data[] = [
'id' => $product->id,
'packages ' => $packages,
]
}
EDIT:
Please try again with a revised version of the code you provide below.
foreach ( $products as $product ) {
$sums = 0;
$packages = [];
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
}

Resources