I am trying to count the number of elements that are equal to a certain value but im struggling to get to the element that i want to compare, when i run:
{{dd($numberofnotifications)}}
I get the following:
But the value i need to compare is under 'attributes'
so how do i get to the values under attributes?
When i print out each element of the array i get the following format:
{"id":"96a40ebb-a2d1-44d8-9600-e94dd026f152","type":"App\\Notifications\\CommentCreated","notifiable_type":"App\\User","notifiable_id":1,"data":{"comment_id":9,"data":{"name":"John","date":"2020-12-30T08:37:47.000000Z","email":"John#gmail.com","post":2,"body":"test"},"message":"John commented on your post"},"read_at":null,"created_at":"2020-12-30T08:37:47.000000Z","updated_at":"2020-12-30T08:37:47.000000Z"}
It seems that the items is an array of DatabaseNotifications. So, you can get each element manually by its index:
$numberofnotifications[0]->id;
// or
$numberofnotifications[0]->type
or you can use foreach loop:
foreach ($numberofnotifications as $notification) {
$notification->id;
}
As the result is a collection, you can convert them using
$numberofnotifications->toArray();
you'll need to use foreach to iterate through the collection:
foreach($numberofnotification as $number)
{
$number->name; //name here is the "name" of the attribute you want to access
}
if you want to store them in an array then:
foreach($numberofnotification as $number)
{
$attributes[]=$number->name; //name here is the "name" of the attribute you want to access
}
Did you try this
//consider that $username is the logged in user name
$filtered_count = $numberofnotifications->where('name', $username)->count();
and if you want the record
$filtered = $numberofnotifications->where('name', $username)->all();
Related
I have been trying to filter an Array by its props and not by its value so my original array would be -
const orignalArray =[
{id: 1, name:"jim", email:"jim#mail.com",age:20},
{id: 1, name:"jom", email:"jom#mail.com",age:30}
]
id like to be able to use (n) amount of filters.
My output array would look ideally look like this
const filterList["id","age"]
const newArray=[{name:"jim", email:"jim#mail.com"},{ name:"jom", email:"jom#mail.com"}]
I have tried to use filter() but cant seem to get it to work.
any help is much appreciated.
In this case you aren't filtering the array rather creating a new one based on the original with derived elements from each. To achieve this you can use the array map function to loop over the array and create a new one with new objects without the desired properties, e.g.:
function removeArrayElementProps(arr, propsToRemove) {
return arr.map((element) => {
// Create a copy of the original element to avoid modifying the original
const newElement = {...element};
// Remove the desired properties from the new element
propsToRemove.forEach((propToRemove) => {
delete newElement[propToRemove];
});
// Returning the modified element in map puts it in thew new arry
return newElement;
});
}
Then you simply call:
const newArr = removeArrayElementProps(orignalArray, ['id','age']);
This loops over the array, creates a copy of each element, and removes the specified properties from the element.
I have a collection of $linesheetItems, now I need to loop these $linesheetItems inside a foreach loop and store a seasons array by using line sheet item's season code ($linesheetItem['season']). But according to my current code, it returns an empty array.
Code:
$seasons = [];
foreach($linesheetItems as $linesheetItem) {
$seasons = Season::where('code', $linesheetItem['season'])->get();
}
dd($seasons);
How to achieve this, and what are the modifications should I do to my code?
In your code, you are overriding the $seasons variable each time the loop runs. In order to add an item to an array you have to set $seasons[] = Season::where('code', $linesheetItem['season'])->get();. This will always push a new item into the array. If you want to have custom keys on the array, you can do $seasons['your-key'] = Season::where('code', $linesheetItem['season'])->get();
I have a document in Firebase Firestore like the above picture, i want to modify a single element in "order" array, i know there is no direct way to do it but is there any way?
i tryed the below code
let ww = db.collection("collectionName").document("docName")
let arrayElement = 0
ww.updateData([
"order.\(arrayElement).isHasOffer": true,
"order.\(arrayElement).referenceID": self.referenceID,
"order.\(arrayElement).DosageForm": "dd",
"order.\(arrayElement).GenericName": "test",
"order.\(arrayElement).DISC": 33
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
it's override "order" array (remove all the element and adding only what i pass in the code) -> what if there is 100 elements? should i rewrite them all again
it's also convert it from "Array" type to "map", once converted to "map" i'm not able to read them back as an array
note: i have a unique id for every element in the array
Whenever you want to modify individual elements of an array type field, you have to read the document, modify the array in memory, then update the modified array back to the document.
You will not be able to do this without reading the document first. If you require an atomic update, you can perform this read-then-update procedure in a transaction.
Please bare with a very recent user of Drupal.
I want to create an array out of all examples of the string "url" on a Drupal site.
I've used the method "field_get_items" previously to do something very similar, but I am now trying to access a field collection that is many levels deep into the node's array and I'm not sure that method would work.
$website_urls = array();
$faculty_members = field_get_items('node', $node, 'field_faculty_member');
for ($i = 0; $i < count($faculty_members); $i++) {
$value = field_view_value('node', $node, 'field_faculty_member', $faculty_members[$i]);
$field_collection = $value['entity']['field_collection_item'][key($value['entity']['field_collection_item'])];
$website_urls[] = render($field_collection['field_link']['#items'][0]['url']);
}
An example of one url's location is...
['field_faculty_program'][0]['entity']['field_collection_item'][1842]['field_faculty_member'][0]['entity']['field_collection_item'][1843]['field_link']['#items'][0]['url']
..and another...
['field_faculty_program'][4]['entity']['field_collection_item'][1854]['field_faculty_member'][0]['entity']['field_collection_item'][1855]['field_link']['#items'][0]['url']
What is the method I should be using to collect al of the 'url' strings for placement in an array?
You can actually still use the field_get_items() function but eventually pass it 'field_collection_item' instead for the node type.
Something like this should work:
if ($items = field_get_items('node', $node, 'field_faculty_member')) {
//loop through to get the ids so we can take
//advantage of field_collection_item_load_multiple for
//greater efficiency
$field_collection_item_ids = array();
foreach ($items as $item) {
$field_collection_item_ids[] = $item['value'];
}
if ($field_collection_items = field_collection_item_load_multiple($field_collection_item_ids)) {
foreach ($field_collection_items as $subitem) {
//now we load the items within the field collection
if ($items = field_get_items('field_collection_item', $subitem, 'field_faculty_member')) {
//And you can then repeat to go deeper and deeper
//e.g. a field collection item within a field collection
//for instance to get the urls within your faculty members
//item. Best to break this into functions or a class
//to keep your code readable and not have so many nested
//if statements and for loops
}
}
}
}
Hope that helps!
Scott
I have a perl code which read csv file. It contains grid data which needs to be updated at the front end.
First, here is the perl code which reads data and formats it so that the data can be pushed to front end for display.
my #array;
for my $column ($csv->column_headers) {
my $json = encode_json([ map { $_->{$column} } #$data ]);
push(#array, "$json;");
}
The final data is the #array which is passed to front end javascript code. The contents of #array is as follows.
["1","2"]; ["dd","ddd"]; ["wow","cool"]; ["HOLD","HOLD"];
This data is actually 4 columns with column header names as Id, Name, Comment and type. All these data are bundled up together in #array and passed to Javascript.
var header=[];
header[0] = #array[0];
}
This code above displays the below output if I do a console.log(header[0]); It means it is displaying the first element of the array. but I want to display the first element's element.
["1", "2"]
whereas it should display below output.
["1"]
In short, I want to know how can I access array elements elements. I tried using below code but it didn't work. Can someone please suggest?
var header=[];
header[0] = #array[0][0];
I am ultimately trying to put this data in grid by using below code.
for (var i=0;i<row_cnt;i++){
var row={};
row["Id"]=Id[i];
row["Name"]=Name[i];
row["Comment"]=Comment[i];
row["type"]= type[i];
data[i]=row;
}
where Id[i] will corresponding to "1" in first loop and "2" in second loop. Similarly it will generate data for other columns. These are then assigned to rows and updated in grid.
As per matts suggestion, I edited the code like this
my $json = encode_json($data);
for my $column ($csv->column_names) {
push(#data_array, "var $column= $json;");
}
Now it displays below values at every cell of the grid.
[object Object]
Building on the answer to your previous question, I think you just need to swap out the loop at the end for this:
my $json = encode_json($data);
print "var data = $json;\n";