I have a table of data and I need to fetch an array from it, that looks like this:
[
['Mon', 25],
['Tue', 13],
['Thu', 25]
]
I'm achieving this through some collection acrobatics. At some point I am mapping the collection adding the numerical value of that day (1 Monday, 2 Tuesday) as a key, so I can sortKeys() later.
The problem is not all days are always present and I want to add them with a value of 0 at their respective place.
My first attempt was foreach on an array of days of the week, and if
$collection->flatten()->search($day) returns false, prepend that day. This works fine, but Thu always get appended. It never returns true on the search even though it's copied and pasted and should be identical. All other days are skipped/prepended correctly...
Then I tried array_search on toArray() and the same thing happened. Thu never returns true ...
This is extremely weird, basically Thu == Thu returns false
Is there anyway I can use array_merge or something like that to make it better (or get it working at all?).
This is one way of doing it. It could be done much cleaner, if your data was structured different in the first place, like using day name/value as key, instead of having both in sub arrays, but I will keep to the original question:
$defaultDays = collect([
['Mon', 0],
['Tue', 0],
['Wed', 0],
['Thu', 0],
['Fri', 0],
['Sat', 0],
['Sun', 0],
]);
$days = [
['Mon', 25],
['Tue', 13],
['Thu', 25]
];
// Use $defaultDays to map, as we will need all seven days no matter what.
$days = $defaultDays->map(static function (array $defaultDay) use ($days) {
// Current match is the default day...
$match = $defaultDay;
foreach ($days as $day) {
if ($day[0] === $defaultDay[0]) {
$match = $day;
}
}
return $match;
});
This will result in:
Illuminate\Support\Collection {#1388
#items: array:7 [
0 => array:2 [
0 => "Mon"
1 => 25
]
1 => array:2 [
0 => "Tue"
1 => 13
]
2 => array:2 [
0 => "Wed"
1 => 0
]
3 => array:2 [
0 => "Thu"
1 => 25
]
4 => array:2 [
0 => "Fri"
1 => 0
]
5 => array:2 [
0 => "Sat"
1 => 0
]
6 => array:2 [
0 => "Sun"
1 => 0
]
]
}
Related
i have this array:
$ingredients_alergens = [
1285 => [ //id from ingredient
4, //id from alergen
2
]
1286 => [
6
]
1287 => [
1
]
1288 => [
9
]
]
and i want make a massive sync similar to this:
$ingredient->alergens()->sync([1,3,8]);
but with all the array. I want make a únic sync/upsert/something for a full list and don't do query to query. Because i have arrays/jsons from more than a thousand redords.
Are there any way to build a massive sync (into single query, like an upsert) into eloquent laravel?
You have many Ingredients (1285, 1286, 1287, 1288), so you'd need to get all of them first and then, for each of them, sync the relationship.
You could do it with these 2 lines using your $ingredients_alergens variable:
$ingredients_alergens = [
1285 => [4, 2],
1286 => [6],
1287 => [1],
1288 => [9],
];
Ingredient::findMany(array_keys($ingredients_alergens)) // findMany([1285, 1286, 1287, 1288])
->each(fn(Ingredient $i) => $i->alergens()->sync($ingredient_alergens[$i->id]));
If you do not want sync to delete existing alergens. (For example, you just want to add alergen 9 to ingredient 1288), use syncWithoutDetaching() instead of sync().
I got this array:
What I want to do next is to make a collection from the array and I write:
$variant_images = collect($p->images);
but I got the error:
"Undefined index: images"
What's bad in my code and how to solve it?
Assuming $p is array like this
$p = [
'images' => [
1, 2, 3, 4
]
];
you can write
$collection = collect($p);
// access the images
var_dump($collection->get('images'));
and the output would be
array:4 [▼
0 => 1
1 => 2
2 => 3
3 => 4
]
This is my array data from
$users = [1, 2, 3, 4];
$bidder = [3, 6, 7, 2];
And i want to sort like this
users_id | bidder
---------- ** ----------
4 | 2
1 | 3
2 | 6
3 | 7
and In Controller,using Collections I sort in this way
$users=$request->user_id;
$bidder=$request->bidder_rate;
$data = collect($users)->map(function ($user, $key) use ($bidder) {
return [
'user_id' => $user,
'bidder' => $bidder[$key]
];
})->sortBy('bidder');
Now when i do dd($data).It worked
1 => array:2 [▼
"user_id" => "2"
"bidder" => "10"
]
0 => array:2 [▼
"user_id" => "1"
"bidder" => "12"
]
2 => array:2 [▼
"user_id" => "4"
"bidder" => "15"
]
But now i want to save all user_id and bidder sorted data in respective field(user_id & bidder) in
array form.So how can i store them
$auction=new Auction();
$auction->name=$data['auction_name'];
$auction->user_id=$data['user_id']; //I think i cannot do like this
$auction->bidder=$data['bidder'];
Try this
$auction=new Auction();
$auction->name=collect($data)->pluck("user_id");
$auction->user_id=collect($data)->pluck("bidder");
$auction->bidder=$data['bidder'];
hi im using Maatwebsite with laravel everything working so good so far ..
but i want to update excel like this ..
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
2 2020-02-02 20
2 2020-02-02 -20
3 2020-03-03 50
3 2020-03-03 -50
3 2020-03-03 40
3 2020-03-03 -40
what i want thats the sum of the amount with number 1 sould return 0 or end the import
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
how can i check this (10 + -5 + -5 == 0) or fail
and for 2 and 3 ect ..
thanks a lot
I explained all the steps in comments but I will explain here as well.
When you loop through each row, you first need to grab all the rows where number field is 1, 2 or 3, what ever the number is currently in the iteration.
In this case, the first loop results will be:
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
Then you sum (add up) the values from the amount column.
In this case, it will sum like this:
10
-5
-5
-----
0
If the answer is not 0, take the current sheet ($sheet) and return what you currently have, to be exported.
Full class:
...
use Maatwebsite\Excel\Concerns\FromArray;
class ExampleExport implements FromArray
{
public function array() : array
{
// EXAMPLE hardcoded data for the purpose of this demo
$rows = [
[
'number' => 1,
'date' => '2020-01-01',
'amount' => 10
],
[
'number' => 1,
'date' => '2020-01-01',
'amount' => -5
],
[
'number' => 1,
'date' => '2020-01-01',
'amount' => -5
],
[
'number' => 2,
'date' => '2020-02-02',
'amount' => 20
],
[
'number' => 2,
'date' => '2020-02-02',
'amount' => -20 // <-------- Change this to -21 to test
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => 50
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => -50
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => 40
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => -40
],
];
// EXAMPLE hardcoded data for the purpose of this demo
$rows = collect($rows);
// You probably going to get this from your database so should look like this:
// $rows = \App\Model::all(['number', 'date', 'amount']); // OR below
// $rows = DB::table('examples')->select(['number', 'date', 'amount'])->get();
// Blank sheet
$sheet = [];
foreach ($rows as $row) {
// Get all the rows where the `number` field has the same value,
// for example 1, 2, or 3, then sum the `amount` field (add up).
//
// If the amount does not add up to 0, stop and return what you currently got
if ($rows->where('number', $row['number'])->sum('amount') !== 0) {
return $sheet;
}
// Else, add them to the sheet and continue.
$sheet[] = $row;
}
return $sheet;
}
}
Results:
When amount adds up to 0:
When amount does not add up to 0:
This the data when user submit the form :
POST Data
_token
"JNDt8WC6kVbvrSdFTKSGnHsfzTuIsbthslf5Gqjs"
invoice_number
"15"
dateofbill
"2019-04-19"
customer_name
"praveen kumar tiwari"
customer_mobile
"8924001750"
sno
array:3 [▼
0 => "1"
1 => "2"
2 => "3"
]
item_name
array:3 [▼
0 => "jeans"
1 => "shirt"
2 => "lower"
]
qty
array:3 [▼
0 => "2"
1 => "3"
2 => "2"
]
price
array:3 [▼
0 => "20000"
1 => "232"
2 => "12"
]
gst
array:3 [▼
0 => "1200"
1 => "22"
2 => "12"
]
discount
array:3 [▼
0 => "100"
1 => "23"
2 => "12"
]
textarea
""
i cannot be able to store this data into a table. i am trying with for loop but getting an error "Undefined offset: 3".
Code inside the controller
for($i=0;$i<=count($request['sno']);$i++)
{
$invoice = new Invoice;
$invoice->sendbill_id=$bill->id;
$invoice->sno=$request['sno'][$i];
$invoice->item_name=$request->item_name[$i];
$invoice->qty=$request->qty[$i];
$invoice->price=$request->price[$i];
$invoice->gst=$request->gst[$i];
$invoice->discount=$request->discount[$i];
$invoice->save();
}
i want to store these 3 values comming in the array form (sno,item_name,qty,price,gst,discount) in 3 diffrent rows
You should try to use laravel eloquent to save it. Here is some example that you can check it out. Laravel : Many to many insertion
The problem you have is indeed your loop: for($i=0;$i<=count($request['sno']);$i++).
To be specific it is this right here <=:
$i<=count()
^^
Take a look at your array:
[
0 => "1"
1 => "2"
2 => "3"
]
You got a total of 3 objects. count($request['sno']) will therefore return 3 since the count() function does not start counting at 0!
However, calling an index (e.g. $request['sno'][1]) will not return the first object (0 => "1") but the second (1 => "2"). I think you see where I am going.
Since the loop will go on until $i equals 3 the loop will be completed 4 times. At the last time (where $i == 3) you try to get the 4th item out of your array which does not exist so an error message pops up: Undefined offset: 3.
To solve this just change this
$i<=count()
^^
to <. The loop will only be executed if $i is still smaller then 3. This is the case if $i == 2. No error message will pop up.
I do not want to attack or hurt you in any way, but it seems to me that you are relatively new to PHP. Of course, that's not a shame, but I'm wondering if a huge framework like Laravel is right for you. First the basics, then comes the advanced.
But that's only as a small comment and tip from me.