How to prepare PHP multidimensional arrays for Laravel Mass updateOrCreate()? - php

I am trying to mass insert into Laravel (5.6) Model. Having issues with array preparations; It returns
lluminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list'
(SQL: insert into `_geolocation` (`0`, `1`, `2`, `3`, `4`) values
(Manchester,+UK, Manchester,+UK, Manchester,+UK, Manchester,+UK,
Manchester,+UK))
I am generating arrays like this:
if($outputTo->status->message == "OK"){ // if
for ($i = 0; $i < $outputTo->total_results; $i++) {
//print_r($outputFrom->results[$i]->geometry->lat);
$geodata_b [] =[
$formattedAddrTo,
$outputTo->results[$i]->formatted,
$outputTo->results[$i]->geometry->lat,
$outputTo->results[$i]->geometry->lng,
];
}
}
This are my array`s output;
array:5 [▼
0 => array:4 [▼
0 => "Manchester,+UK"
1 => "Manchester, Greater Manchester, England, United Kingdom"
2 => 53.4791301
3 => -2.2441009
]
1 => array:4 [▼
0 => "Manchester,+UK"
1 => "Chapel Street Primary School, Chapel Street, Manchester M19 3GH, United Kingdom"
2 => 53.443957
3 => -2.1858478
]
2 => array:4 [▼
0 => "Manchester,+UK"
1 => "The Manchester, Lytham Road, Bispham FY1 6AH, United Kingdom"
2 => 53.8067298
3 => -3.0549142
]
3 => array:4 [▼
0 => "Manchester,+UK"
1 => "The Manchester, Bromsgrove Road, Bromsgrove B62 0HH, United Kingdom"
2 => 52.4003403
3 => -2.0539726
]
4 => array:4 [▼
0 => "Manchester,+UK"
1 => "The Harlequin, Spitalfields, Sheffield S3 8GG, United Kingdom"
2 => 53.3884864
3 => -1.4663405
]
]
Inserting code;
$geolCache = \App\Geolocation::updateOrCreate([$geodata_b]);
My Model;
protected $fillable = ['adrr','faddr','lat','lng'];
Please could anybody help me how to fix this issue?

You are not following key-value pairs. Try this code
if($outputTo->status->message == "OK"){ // if
for ($i = 0; $i < $outputTo->total_results; $i++) {
$geodata_b [] = [
'adrr' => $formattedAddrTo,
'faddr' => $outputTo->results[$i]->formatted,
'lat' => $outputTo->results[$i]->geometry->lat,
'lng' => $outputTo->results[$i]->geometry->lng,
];
}
}

Related

php Keeping only 1 date occurence in multi-dimensional array

I have this array with certain brand_ids, within these brands I have an array of dates in which a sale occured but these are based on the products in sale so they may appear multiple times on the same brand_id;
This is my array:
array:5 [▼
2 => array:3 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
]
3 => array:5 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
3 => "2022-05-08"
4 => "2022-05-08"
]
4 => array:1 [▼
0 => "2022-05-08"
]
1 => array:3 [▼
0 => "2022-05-01"
1 => "2022-05-08"
2 => "2022-05-08"
]
6 => array:3 [▼
0 => "2022-05-08"
1 => "2022-05-08"
2 => "2022-05-08"
]
]
The code to generate this :
pastSales = [];
$historySales = SaleHistoryCount::all()->toArray();
foreach($historySales as $key => $historySale) {
$saleDateToCompare = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['sale_date'])
->format('Y-m-d');
if(in_array($saleDateToCompare , $saleDays)) {
if(! isset($pastSales[$historySale['sale_date']])) {
$pastSales [$historySale['brand_id']][] = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['brand_id'])
->format('Y-m-d');
}
}
}
$saleDays is a 2D array of every sunday untill a certain year like so
[
"2022-05-08"
"2022-05-15"
"2022-05-22"
]
All the duplicates stripped out and have it reduced to one unless the date is different per brand_id but I can't seem to be able to produce that with array_unique, array_mapping and/or array_columns... How would I achieve the output below?
array:5 [▼
2 => array:3 [▼
0 => "2022-05-08"
]
3 => array:5 [▼
0 => "2022-05-08"
]
4 => array:1 [▼
0 => "2022-05-08"
]
1 => array:3 [▼
0 => "2022-05-01"
2 => "2022-05-08"
]
6 => array:3 [▼
0 => "2022-05-08"
]
]
Use in_array as Tim Lewis proposed:
foreach($historySales as $key => $historySale) {
$saleDateToCompare = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['sale_date'])
->format('Y-m-d');
if(in_array($saleDateToCompare , $saleDays)) {
$date_formatted = Carbon::createFromFormat('Y-m-d H:i:s', $historySale['brand_id'])->format('Y-m-d');
// !!! Is this string correct? Maybe we should check for "$historySale['brand_id']" existance?
if(! isset($pastSales[$historySale['sale_date']]))
$pastSales[$historySale['brand_id']] = [];
if( !in_array($date_formatted, $pastSales[$historySale['brand_id']]) )
$pastSales[$historySale['brand_id']][] = $date_formatted;
}
}

getting emptied while checking if an array value exists - laravel?

I wanted to insert the id values of $courseCat if that id is not present in $m.In the below code, i feel the $m array is getting emptied every time and so, all id's are getting inserted to the $m ,as the result of dump($m) indicates.How can i fix this?
$m=[];
$courseCat = MyCourse::where('course_id', $key['courseId'])->get()->toArray();
foreach($courseCat as $k=>$c){
// dump($courseCat);
if(!in_array($c['id'],$m)){
array_push($m,$c['id']);
}
}
//dump($m);
dump($courseCat); shows the following result
array:2 [
0 => array:19 [
"id" => 2
"course_id" => 18
]
1 => array:19 [
"id" => 3
"course_id" => 18
]
]
array:2 [
0 => array:19 [
"id" => 2
"course_id" => 18
]
1 => array:19 [
"id" => 3
"course_id" => 18
]
]
array:2 [
0 => array:19 [
"id" => 5
"course_id" => 1
]
1 => array:19 [
"id" => 6
"course_id" => 1
]
]
array:2 [
0 => array:19 [
"id" => 5
"course_id" => 1
]
1 => array:19 [
"id" => 6
"course_id" => 1
]
]
dump($m) shows the below result:
array:2 [
0 => 2
1 => 3
]
array:2 [
0 => 2
1 => 3
]
array:2 [
0 => 6
1 => 5
]
array:2 [
0 => 6
1 => 5
]
Below attached images are the result of the query MyCourse::where('course_id', $key['courseId'])->get().
[enter image description here]1
[enter image description here]2
[enter image description here]3
Expected result :
dump($m) should show the below result
[0=>2,
1=>3,
2=>5,
3=>6]
I think it's because you have an outer loop not shown in the question. You need to declare $m before the outer loop:
$m=[];
foreach($keys as $key){
$courseCat = MyCourse::where('course_id', $key['courseId'])->get()->toArray();
foreach($courseCat as $k=>$c){
if(!in_array($c['id'],$m)){
array_push($m,$c['id']);
}
}
}
dump($m);
If you want all the values of a column from your query you can use pluck:
MyCourse::where('course_id', $key['courseId'])->pluck('id')
Now you have a list of all the 'id's.
Laravel 8.x Docs - Database - Running Database Queries - Retrieving a List of Column Values pluck

How to get values from an array in Laravel

I have a 3 level category. I need to gain businesses on level 3 category.
I write this code:
$main_cat = Category::where(['slug' => $url])->first();
$lev_cat2 = Category::where(['parent_id' => $main_cat->id, 'status' => '1'])->get();
foreach ($lev_cat2 as $subCategory) {
$cat_ids_lv2[] = $subCategory->id . ',';
}
foreach ($lev_cat2 as $subCat) {
$lev_cat3[] = Category::where(['parent_id' => $subCat->id, 'status' => '1'])->pluck('id')->toArray();
}
dd($lev_cat3);
Then I got this array which is correct:
array:5 [▼
0 => array:3 [▼
0 => 145
1 => 146
2 => 147
]
1 => array:3 [▼
0 => 148
1 => 149
2 => 150
]
2 => array:3 [▼
0 => 151
1 => 152
2 => 153
]
3 => array:3 [▼
0 => 154
1 => 155
2 => 156
]
4 => []
]
now I dont know how can I get values like 145,146,147,148,149,... to pass theme to
Business::where(['category_id'=> [145,146,147,148,...]]->get();
of course dynamic.
You can use laravel collection helpers :
Business::whereIn('category_id', collect($lev_cat3)->flatten()->all())->get();
Since PHP 5.5.0 there is a built-in function array_column which does exactly this.
You can use it to Converting php array of arrays into single array then use it like this
$category_ids = array_column($lev_cat3);
Business::where(['category_id'=> $category_ids]]->get();

How to sort multidimensional array in ascending form?

Here is the array. What I want is I wanna sort the array on the basis on 'income_difference' in ascending order. If possible, I just want 3 data with least income difference.
array:5 [▼
0 => array:4 [▼
"month" => "11"
"income_times" => 2
"income_amount" => 52300
"income_difference" => 49000
]
1 => array:4 [▼
"month" => "10"
"income_times" => 1
"income_amount" => 50000
"income_difference" => 46700
]
2 => array:4 [▼
"month" => "09"
"income_times" => 1
"income_amount" => 5000000
"income_difference" => 4996700
]
3 => array:4 [▼
"month" => "08"
"income_times" => 1
"income_amount" => 50000
"income_difference" => 46700
]
4 => array:4 [▼
"month" => "06"
"income_times" => 1
"income_amount" => 5200
"income_difference" => 1900
]
]
Use usort:
usort($data, function($a, $b) {
return $a['income_difference'] - $b['income_difference'];
});
If you don't want to maintain the index(0,1,2,3) you can use usort
e.g
function cmp($a, $b)
{
if ($a['income_difference'] == $b['income_difference']) {
return 0;
}
return ($a['income_difference'] < $b['income_difference']) ? -1 : 1;
}
usort($yourArray,'cmp')
If you want to maintain the index (0,1,2,3) you can use uasort instead of usort. Other syntax remains the same.
For more details on functionality please refer usort

Concatenate strings from 2 array based on key

so i have a bit difficulty in combining arrays in php. So let say i have these 2 array
array:4 [▼
20 => "University"
21 => "Polic Station"
22 => "Ambulance"
1 => "Zoo"
]
array:4 [▼
20 => "abc"
21 => "def"
22 => "ghi"
1 => "jkl"
]
How do i actually combine this to this
array:4 [▼
20 => "abc University"
21 => "def Polic Station"
22 => "ghi Ambulance"
1 => "jkl Zoo"
]
Here's the result:
$arr = array(
20=>'University',
21=>'Polic Station',
22=>'Ambulance',
1=>'Zoo');
$arr2= array(
20=>'abc',
21=>'def',
22=>'ghi',
1=>'jkl');
$arr_out = array();
foreach($arr as $key=>$el) {
$arr_out[$key] = $arr2[$key] ." ".$el;
}
var_dump($arr_out);
Obviously, you'll need to keep in mind to check whether the key exists in the second array so you do not get an error when accessing the value.

Categories