I'm trying to create an array to convert JSON. My data is queried from database.
My problem is I have to check condition for array. If $item->verified == 1, my 'isVerified'
will be true, my email will be in verified and opposite.
Here is what I did, I check condition and create 2 array for it. Can I just use 1 array
for condition:
if( ($item->verified) == 1)
{
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => true,
'email' => [
'verified' => $item->email,
'unverified' => []
]
];
}
else
{
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => false,
'email' => [
'verified' => [],
'unverified' => $item->email
]
];
}
You can use ternary operator.
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => $item->verified == 1,
'email' => [
'verified' => $item->verified == 1 ? $item->email : [],
'unverified' => $item->verified == 0 ? $item->email : [],
]
];
Related
I'm trying to tweak the call to the Carrot2 REST API :
$client = new Client();
try {
$params = [
'multipart'=> [
['name'=> 'dcs.c2stream', 'contents' => $xml],
['name' => 'dcs.algorithm', 'contents' => 'lingo'],
['name' => 'dcs.output.format', 'contents' => 'JSON'],
['name' => 'dcs.clusters.only', 'contents' => 'true'],
['name' => 'MultilingualClustering.defaultLanguage', 'contents' => 'FRENCH'],
['name' => 'preprocessing.labelFilters.minLengthLabelFilter.minLength', 'contents' => 5],
['name' => 'preprocessing.documentAssigner.minClusterSize', 'contents' => 4]
],
'debug' => false
];
$response = $client->request('POST', 'http://devbox:8080/dcs/rest', $params);
The lingo parameters 'preprocessing.labelFilters.minLengthLabelFilter.minLength' and 'preprocessing.documentAssigner.minClusterSize' have no impact in the request.
I've found them in the documentation of the lingo algorithm.
Thanks for help !
With the good docker image, everything is fine (docker pull touane/carrot2) :
$c2Payload = [
'algorithm' => 'Lingo',
'language' => 'French',
'parameters' => [
'preprocessing' => [
'documentAssigner' => [
'minClusterSize' => 4
],
'labelFilters' => [
'minLengthLabelFilter' => [
'minLength' => 8
],
'completeLabelFilter' => [
'labelOverrideThreshold' => 0.35
]
]
],
'scoreWeight' => 1, // Tri par score
'clusterBuilder' => [
'phraseLabelBoost' => 2.5
],
'dictionaries' => [
'wordFilters' => [
['exact' => $this->getParameter('carrot2')['stop_words']]
]
],
'matrixBuilder' => [
'termWeighting' => [
'#type' => 'LinearTfIdfTermWeighting'
],
'boostFields' => ['title']
]
],
'documents' => []
];
$client = new Client();
$params = [
'body' => json_encode($c2Payload ),
'debug' => false
];
$response = $client->request('POST', $this->getParameter('carrot2')['url'], $params);
I'm trying to create a kind of dataset using laravel Collections, for this I'm using the "times" method:
function getValidData(int $amount): Collection
{
return Collection::times($amount, function (int $number): array {
$password = faker()->password(8, 12);
return [
"User #{$number}" => [
'name' => faker()->firstName(),
'email' => faker()->unique()->safeEmail(),
'password' => $password,
'password_confirmation' => $password
]
];
});
}
However, the result is not as I expected:
[
0 => [
'User #1' => [
'name' => 'ana',
'email' => 'ana#email.com',
'password' => '12345678',
'password_confirmation' => '12345678'
]
],
1 => [
'User #2' => [
'name' => 'leo',
'email' => 'leo#email.com',
'password' => '3231232132',
'password_confirmation' => '3231232132'
]
]
]
I was hoping it would be:
[
'User #1' => [
'name' => 'ana',
'email' => 'ana#email.com',
'password' => '12345678',
'password_confirmation' => '12345678'
],
'User #2' => [
'name' => 'leo',
'email' => 'leo#email.com',
'password' => '3231232132',
'password_confirmation' => '3231232132'
]
]
I can solve this using array_merge(...(Collection::times...)) but it seems a kinda off... Is there any way to solve this in a cleaner way using Collections?
If you would like to map the collection with new keys, you could do the following, using the mapWithKeys() function.
Example
$users = collect(range(1, $amount))
->mapWithKeys( function($index) {
$password = faker()->password(8, 12);
return [sprintf("User #%d", $index) => [
'name' => faker()->firstName(),
'email' => faker()->unique()->safeEmail(),
'password' => $password,
'password_confirmation' => $password,
]];
});
This will run from 1 to the specified $amount. Example output with 3 users:
Illuminate\Support\Collection {#2016
#items: array:3 [
"User #1" => array:4 [
"name" => "Garret"
"email" => "aurelio03#example.com"
"password" => "Vp=Et3!?w0"
"password_confirmation" => "Vp=Et3!?w0"
]
"User #2" => array:4 [
"name" => "Genoveva"
"email" => "hilda.bins#example.net"
"password" => "W?miL1Kts"
"password_confirmation" => "W?miL1Kts"
]
"User #3" => array:4 [
"name" => "Zella"
"email" => "mmurray#example.net"
"password" => "g8)"pYgjQ~"
"password_confirmation" => "g8)"pYgjQ~"
]
]
}
You could also chain the toArray() method on the collection if you prefer an Array over a Collection.
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']
] : []));
I have a Laravel Collection of items:
[
[
'id' => 1,
'path' => '/',
'created_at' => '2020-05-20 20:12:00'
],
[
'id' => 2,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:01:00'
],
[
'id' => 3,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:21:00'
],
[
'id' => 4,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:09:00'
],
[
'id' => 5,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:10:00'
],
]
This is the raw data that would be found in the collection if I cast it to an array, but I need it to remain in collection format.
I need to remove any duplicates where the current item has the same path and is less than 5 minutes old compared to the previous item.
So in this case, item #4 would be removed leaving only #5, but items #2 and #3 would be kept even tho their paths are the same.
How would I do this?
Use the following namespace in your controller file:
use DateTime;
Use the following code in your controller file:
$collection = [
[
'id' => 1,
'path' => '/',
'created_at' => '2020-05-20 20:12:00'
],
[
'id' => 2,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:01:00'
],
[
'id' => 3,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:21:00'
],
[
'id' => 4,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:09:00'
],
[
'id' => 5,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:10:00'
],
];
$paths = [];
$time_count = [];
foreach ($collection as $key => $data) {
if (in_array($data['path'], $paths)) {
$arr_pos = array_search($data['path'], array_values($paths));
$datetime1 = new DateTime($data['created_at']);
$datetime2 = new DateTime($collection[$arr_pos]['created_at']);
$interval = $datetime1->diff($datetime2);
$mins = $interval->format('%i');
if ($mins < 5) {
unset($collection[$arr_pos]);
}
}
$paths[] = $data['path'];
}
This will return result:
array:4 [▼
0 => array:3 [▼
"id" => 1
"path" => "/"
"created_at" => "2020-05-20 20:12:00"
]
1 => array:3 [▼
"id" => 2
"path" => "/somewhere"
"created_at" => "2020-05-20 21:01:00"
]
2 => array:3 [▼
"id" => 3
"path" => "/somewhere"
"created_at" => "2020-05-20 21:21:00"
]
4 => array:3 [▼
"id" => 5
"path" => "/somewhere/else"
"created_at" => "2020-05-20 21:10:00"
]
]
I hope this works for you.
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);