PHP Array Sort and group - sorting

Below is an array with count and its button url, need to sort and group duplicate items in new array and sorted:
$array = [[
[1,'Firsts','https://test.com/button-1', ''],
[1,'Seconds','https://test.com/button-2', ''],
[2,'Testing-Button','https://test.com/copy.jpg', ''],
[19,'LetsStart','https://test.com/', ''],
[4,'Firsts','https://test.com/button-3', ''],
[5,'Seconds','https://test.com/button-4', ''],
[10,'Firsts','https://test.com/button-5', '']
]];
Expected Output:
$output = [[
[1,'Firsts','https://test.com/button-1', ''],
[1,'Seconds','https://test.com/button-2', ''],
[2,'Testing-Button','https://test.com/copy.jpg', ''],
[19,'LetsStart','https://test.com/', '']
],
[
[4,'Firsts','https://test.com/button-3', ''],
[5,'Seconds','https://test.com/button-4', '']
],
[
[10,'Firsts','https://test.com/button-5', '']
]
];

Related

Best way to update a lot of data with difference value?

I have a lot of data and each record have difference value. I try to loop insert/update data but it take time. Is it have better way to improve my code?
I don't want to delete all data before update.
$data = [
[ 'id' => 1, 'name' => 'A' ],
[ 'id' => 2, 'name' => 'B' ],
[ 'id' => 3, 'name' => 'C' ],
[ 'id' => 4, 'name' => 'D' ],
.
.
.
[ 'id' => 10000, 'name' => 'ZYX' ],
]
foreach ($data as $item) {
DB::table('my_table')->updateOrInsert(['id' => $item->id], $item);
}
Thank.
You can use upsert in Laravel 8.x or use this package: https://github.com/staudenmeir/laravel-upsert to use INSERT ON DUPLICATE
$data = [
[ 'id' => 1, 'name' => 'A' ],
[ 'id' => 2, 'name' => 'B' ],
[ 'id' => 3, 'name' => 'C' ],
[ 'id' => 4, 'name' => 'D' ],
.
.
.
[ 'id' => 10000, 'name' => 'ZYX' ],
];
DB::table('my_table')->upsert($data, 'id');
use laravel upsert method here
for example you want to update if exists or insert record if not exists
$data = [
[
'id' => 1
'name' => 'J.K. Rowling',
'author' => 'Harry Potter',
'quantity' => 15
],
[
'id' => 2
'name' => 'Cal Newport',
'author' => 'Deep Work',
'quantity' => 20
]
];
DB::table('books')->upsert($data, ['id'], ['quantity']);
1.The first argument consists of the values to insert or update.
2.The second argument lists the column(s) that uniquely identify records (id in our case) within the associated table.
3.The third and final argument is an array of columns that should be updated if a matching record already exists in the database. We want the quantity to be updated in our case.
for more detail read official docs upsert

Laravel: Validate an array of strings

How to validate that fruits from a given $list are in the allowed list ?
$attributes [
"fruits" => ['nullable', 'string', 'in:apple,banana,orange'],
];
$list = [
"fruits" => [
"apple",
"orange"
]
];
$validator = Illuminate\Support\Facades\Validator::make($list, $attributes);
you can validate each item in this array individually:
$attributes = [
"fruits.*" => ['nullable', 'string', Rule::in(['apple','banana','orange'])],
];

Using Conditional Statement in updateOrCreate

before updating i need to check if a particular value is empty. if its empty avoid updating that column
DrmCustomer::updateOrCreate([
'email'=> isset($row['email']) ? $row['email'] : "",
'user_id'=> $user_id,
],[
(isset($row['fieldMobilePhone']['value'])) ?: 'phone'=> $row['fieldMobilePhone']['value'],
(isset($row['fieldWebsite']['value'])) ?: 'website'=> $row['fieldWebsite']['value'],
(isset($row['fieldStreet1']['value'])) ?: 'address'=> $row['fieldStreet1']['value'],
(isset($row['fieldCity']['value'])) ?: 'city'=> $row['fieldCity']['value'],
(isset($row['fieldState']['value'])) ?: 'state'=> $row['fieldState']['value'],
(isset($row['fieldZip']['value'])) ?: 'zip_code'=> $row['fieldZip']['value'],
(isset($row['fieldCountry']['value'])) ?: 'country'=> $row['fieldCountry']['value'],
'default_language'=> 'DE',
'currency'=> 'EUR',
'insert_type'=> 'API'
]);
You can use Laravel Collection to filter your data by using following technique
<?php
$mapFields = [
'fieldMobilePhone' => 'phone',
'fieldWebsite' => 'website',
'fieldStreet1' => 'address',
'fieldCity' => 'city',
'fieldState' => 'state',
'fieldZip' => 'zip_code',
'fieldCountry' => 'country',
];
$validKeys = array_keys($mapFields);
$collection = collect($row);
$data = $collection->filter(function($value, $key) use($validKeys){
return Arr::get($value, 'value' false) && in_array($key, $validKeys);
})->flatMap(function($value, $key) use($mapFields){
return [
$mapFields[$key] => $value['value']
];
})->merge([
'default_language'=> 'DE',
'currency'=> 'EUR',
'insert_type'=> 'API'
])->all()->toArray();
DrmCustomer::updateOrCreate([
'email'=> Arr::get($row, 'email', ''),
'user_id'=> $user_id,
], $data);
I was able to do that like this:
DrmCustomer::updateOrCreate(['email' => isset($row['email']) ? $row['email'] : '', 'user_id' => $user_id], [
'default_language'=> 'DE',
'currency'=> 'EUR',
'insert_type'=> 'API'
] + (isset($row['fieldMobilePhone']['value']) ? [
'phone' => $row['fieldMobilePhone']['value']
] : []) + (isset($row['fieldWebsite']['value'])) ? [
'website' => $row['fieldWebsite']['value']
] : []) + (isset($row['fieldStreet1']['value']) ? [
'address' => $row['fieldStreet1']['value']
] : []) + (isset($row['fieldCity']['value']) ? [
'city' => $row['fieldCity']['value']
] : []) + (isset($row['fieldState']['value']) ? [
'state' => $row['fieldState']['value']
] : []) + (isset($row['fieldZip']['value']) ? [
'zip_code' => $row['fieldZip']['value']
] : []) + (isset($row['fieldCountry']['value']) ? [
'zip_code' => $row['fieldCountry']['value']
] : []));

Search in Laravel Datatables

In my datatables, the search function works only on the name column. The name column ist different that the others. It means, the name column gives the value of the database back, while the others gives a value back with the function add column
In the column array there are the following values:
ยดยดยด
protected function getColumns()
{
return [
'status',
'name' => [
'title' => 'Name',
'orderable' => true,
'searchable' => true
],
'location' => [
'title' => 'Standort',
],
'department' => [
'title' => 'Abteilung',
'orderable' => true,
'searchable' => true
],
'division' => [
'title' => 'Bereich',
'orderable' => true,
'searchable' => true
],
'leader' => [
'title' => 'Verantwortlicher',
'orderable' => true,
'searchable' => true
],
'start_date' => [
'title' => 'Startdatum',
'searchable'=> true,
],
'end_date' => [
'title' => 'Enddatum',
'searchable'=> true
]
];
}
```
Why it doesn't search on all columns? What i have to do?
Try to search by using this code.
return Datatables::of($tasks)
->filter(function ($query) use ($request) {
$title = $request->title;
if (isset($title) && !empty($title)) {
$query->where('title', 'like', '%'.$title.'%');
}
})->make(true);
OR
return Datatables::of($tasks)
->filterColumn('title', function($query, $value) {
$query->whereRaw("title like ?", ["%{$value}%"]);
})->make(true);

Why won't CakePHP 3.2 Paginator sort on my query results?

CakePHP query and such from the controller:
$ratings = $this->Ratings->find('all')->group('manufacturer');
$ratings->select(['manufacturer',
'count' => $ratings->func()->count('*'),
'max' => $ratings->func()->max('psi_score'),
'min' => $ratings->func()->min('psi_score')]);
$ratings = $this->paginate($ratings);
$this->set(compact('ratings'));
$this->set('_serialize', ['ratings']);
Here is what debug($ratings) produces:
'items' => [
(int) 0 => object(Cake\ORM\Entity) {
'manufacturer' => 'A10Green Technology',
'count' => (int) 8,
'max' => '7.41',
'min' => '6.57',
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Ratings'
},
In the view, sorting on manufacturer works fine. That is an original db field. The count, max and min values are not getting sorted.
Here are the sort calls for the view:
<th><?= $this->Paginator->sort('manufacturer')?></th>
<th><?= $this->Paginator->sort('count')?></th>
<th><?= $this->Paginator->sort('max')?></th>
<th><?= $this->Paginator->sort('max')?></th>
You need to whitelist the fields that you want to allow to be sorted like in: Pagination
public $paginate = [
'sortWhitelist' => [
'id', 'title', 'Users.username', 'created'
]
];
Otherwise by default cake 3 blocks it

Resources