Remove duplicate attributes from a collection Laravel - php

For some strange reason, my collection (returned from query) is showing duplicate attribute 4 times exactly. Is there a way to remove duplicate or repeated attributes.
#attributes: array:2 [▼
"name" => "Ram Inden"
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
In this collection, the features attributes only should have 2,3,4 but it's repeated four times, and I don't know why. In my database it's only 2,3,4.
Another thing, this thing only appears at a Live server, my localhost works fine.
Any help would be really appreciated

Use php explode,array_uniqe,join function
$collection = collect([
"name" => "Ram Inden",
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
]);
$unique = join(',', array_unique(explode(',', $collection['features'])));
$collection['features'] = $unique;
return $collection;

Starting from the collection you could eliminate the duplicates in the following way:
$collection = collect([
"name" => "Ram Inden",
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
]);
$str = $collection['features'];
$collection->prepend(implode(',',array_unique(explode(',', $str))) ,'features');
return $collection;

Related

How to array merge in laravel

I have a problem here, I want to combine 2 arrays into 1, I've tried using array_merge from php, and merge () from laravel but nothing works
//$plucked is EAV database
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = array_merge($plucked, $vendor);
// $merged = $vendor->merge($plucked)->all();
dd($merged);
I think because the array is different, there array $plucked
#items: array:10 [▼
"user_email" => "cobaupdatelagi#gmail.com"
]
and there my array in $vendor
array:15 [▼
"vendor_id" => 39
"province" => "ACEH"
]
the output that I want
$somearray =[
"vendor_id" => 39
"province" => "ACEH"
"user_email" => "cobaupdatelagi#gmail.com"
]
Your $vendor is one associative array while $plucked is an array of arrays. Even if it has only one item it will be of index zero so you need to loop through $plucked and merge for each one.
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = [];
foreach($plucked as $p){
$merged[] = array_merge($p, $vendor);
}
dd($merged);
$vendor = Vendor::find($id);
$vendor_detail = Vendor_detail::select('vendor_id','province')->where('vendor_id',$id)->get()->toArray();
$data= array_merge($vendor,$vendor_detail);
I think you should use database join to get faster results.
$vendor = Vendor::join('vendor_details', 'vendors.id', '=', 'vendor_details.vendor_id')
->select('vendors.*', 'vendor_name','vendor_value')
->where('id', $id)
->first();
if ($vendor) {
$vendor = $vendor->toArray();
}
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get(); will give you a collection
as well as $plucked = $vendor_detail->pluck('vendor_name','vendor_value'); will give you a collection, so, either you can use collection merge or you may like to loop through one and add merge another as other answer is doing, but these are not array, you are getting collections.

Compare arays and exclude element form one if it has duplicates in others

I need to compare arrays, if element from first or second array has duplicates in another one I need to exclude it. I know it sound simply and I'm sure it is but i cant handle with that problem :(
So i have first array like this:
Array:3 [
6 => blog/something
4 => blog/somethingElse
5 => blog/else
]
Second array almost identical:
Array:3 [
1 => /blog
2 => /comments
3 => /posts
]
And the last array:
(integer on the left is id of elements in second array, in this example
comments and posts)
Array:2 [
0 => array:2 [
'page_id' => 2
'value' => noindex
]
1 => array:2 [
'page_id' => 3
'value' => noindex
]
]
So if I have element in array first or second which exist in array thrid too AND have value = noindex i need to exclude it.
I have tried do this by foreach recursive, by array_walk_recursive but I still can't get satisfied result
First get all the indices you need to exclude and then exclude them:
$excludeIndices = array_column(array_filter($array3, function ($entry) {
return $entry['value'] === 'noindex';
}), 'page_id');
$keepArray1 = array_diff_key($array1, array_flip($excludeIndices));
$keepArray2 = array_diff_key($array2, array_flip($excludeIndices));
Sandbox
You can filter using the first two arrays directly.
$result = array_filter($last, function($item) use ($first, $second) {
return !($item['value'] == 'noindex' &&
(isset($first[$item['page_id']]) || isset($second[$item['page_id']]))
);
});

How to apply a filter to update element in array of arrays?

I am trying to create a PHP application that lets me uploading data to a MongoDB collection. For that I have "installed" the PHP driver with no problems.
However, I cannot find anyway -neither in the PHP guide- how could I update an element in an array of arrays.
Collection structure
As you may see, _unidades is an array of arrays. Each of those arrays contains an ID, a string and another array. In my case, which will be chosen depends on previous param -it has to match with element 1 of one of them.
Once I have selected that structure, I want to insert a new array into its array of arrays (position 2).
Regarding code, I tried the following:
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->update(
[
'_isbn' => (int) $_POST["isbn"],
'_topics' =>
[
'0' => (int) $_POST["topic"]
]
],
[
'$set' => [
'1' => array($_POST["sentence"], $_POST["question"])
]
]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$resultado = $manager->executeBulkWrite('libreee.faq', $bulk, $writeConcern);
However as you can see I am not capable to determine at least that it doesn't have to be an specific array (7th line).
Once said that I look forward to receiving your help.
Thanks a lot in advance.
Regards,
Ciconia.

PHP Loop through arrays consecutively based on value

I'm having a looping mind-breaking issue which I can't seem to solve myself. Currently working on saving a form input in a webshop. The data:
"personalisation" => array:3 [▼
0 => "embroidery"
1 => "printing"
2 => "embroidery"
]
"repeat" => array:2 [▼
0 => "true"
1 => "true"
]
"selectedColors" => array:1 [▼
0 => "3"
]
The problem which I have here: I need to loop through the personalisation array to add to my DB. With the embroidery, the repeat value is linked and for the printing the selectedColors is linked. How can I loop through the personlisation array and match the values from the other array?
I really wouldn't recommend designing forms like this, you're basically just sending a jumbled mess to your backend with no association.
You can "correct" the association by filtering the personalisation array and reindexing it so the keys match the other arrays.
$embroderies = array_values(array_filter($array['personalisation'], function($item) {
return $item === 'embroidery';
}));
foreach($emborderies as $key => $value) {
// get value from $array['repeat'][$key];
}
I can't think of any other way than to use a helper array for example.
It could be
array('embroidery' => 'repeat', 'printing' => 'selectedColors')
And you start looping through personalization, depending on the value you use it as a key in the helper array, then finally get the wanted value from the array.
1st iteration: 0/embroidery -> embroidery/repeat -> repeat/true
2nd iteration: 1/printing -> printing/selectedColors -> selectedColors/
...

How to find all documents where the value of a field is null or empty

I'm trying to write a simple Mongo query to return all documents where the value of a field is null (or an empty array, I'm not sure what you call it).
Here is my query;
db.getCollection('contact').find({'poco.name.email':false})
Here is a screenshot of my collection using RoboMongo;
Ultimately, I need to transfer this to some PHP. So far I have this working;
$conditions = array_merge($conditions, [
'owner.$id' => $this->getId(),
'poco.name.familyName' => "Smith",
//not sure what goes here.. something like
//'poco.emails' => null,
]);
return Model_Mongo_Contact::getContacts($conditions, $sort, $fields, $limit, $skip);
That's probably going to be harder to answer without more access to the methods.. Or maybe not I am very new to Mongo it might be really obvious.
I'm not PHP expert but I'll be doing in mongo shell as:
db.collection.find({
$and: [
{"poco.email":{$exists: true}},
{"poco.email":{$ne: []}}
]})
Query above will list all documents where poco.name.email is not missing and is not empty.
The basic concept when looking for an "empty" array or even "non-existent" is to use a property of "dot notation" and search where the 0 index of the array does not exist. This can be achieved with using the $exists operator:
$conditions = array_merge($conditions, [
'owner.$id' => $this->getId(),
'poco.name.familyName' => "Smith",
'poco.emails.0' => array( '$exists' => FALSE )
]);
That condition is true when either there is no property at all, or if it is something other than an array ( therefore no "0" field property ) or indeed an "empty" array ( since there is no content at the first index ).
This works best when the field is actually "indexed". So if in your "normal" structure you have "sub-documents" inside the array element with say a consistent field named "address" which is indexed as "poco.emails.address", then you are best of pointing to that specific indexed property to see if it $exists or not:
$conditions = array_merge($conditions, [
'owner.$id' => $this->getId(),
'poco.name.familyName' => "Smith",
'poco.emails.0.address' => array( '$exists' => FALSE )
]);
But if the array consists purely of "values" only and no "sub-documents", then simply testing for the 0 index position of the array as initially demonstrated will be enough.

Categories