My first post here. I tried to search for an answer, but no luck, so here we go
Generally I cannot share with you with the exact code I'm working on :(
so here's the example one:
$collection = collect(['country' => 'Germany', 'city' => 'Berlin', 'month' => 'April']);
dd($collection);
//"country" => "Germany"
//"city" => "Berlin"
//"month" => "April"
$array1 = ['France', 'Paris', 'May'];
$array2 = ['Spain', 'Madrid', 'June'];
My question is - how to "add" those arrays (minding array1 and array2 order) so I end up with something like this?
dd($newCollection);
//output:
//"country" => ["Germany", "France", "Spain"]
//"city" => ["Berlin", "Paris", "Madrid"]
//"month" => ["April", "May", "June"]
OR
If there's a way to get all records from database and make one of the rows a key and a selection of them as values
Example
$users = User::get();
//this table has columns "full_name", "e-mail", "job", "birth_date", "city" and "password"
$collection = <<???>> //make column "full_name" as key and columns "e-mail", "job", "password" as values
dd($collection);
//output:
//"John Doe" => ["johndoe#mail.com", "Janitor", "topsecret"]
//"Jane Doe" => ["janedoe#mail.com", "teacher", "sercretpassword"]
Lifetime gratitude in advance for an answer... I've read Laravel's documentation many times and could not find a solution
I've got this
The solution for me looks like this:
$users = User::get();
//this table has columns "id", "full_name", "e-mail", "job", "birth_date", "city" and "password"
//I don't want to use all columns here
foreach($users as $user=>$value){
$full_name = $value->full_name;
$e-mail = $value->e-mail;
$job = $value->job;
$password -> $value->password;
$endresult[] = [$full_name, $e-mail, $job, $password];
}
$collection = collect($users->keyBy('id')->pluck('id'))->combine($endresult);
dd($collection);
//output:
// 1 => ["John Doe", "johndoe#mail.com", "Janitor", "topsecret"]
// 2 => ["Jane Doe", "janedoe#mail.com", "teacher", "sercretpassword"]
It looks terrible, but works like a charm. I needed to format this like so because in my project there are many foreign keys and I need to pagify my results, so to make it the easiest way possible I need to combine all values to one key (just like a row in csv) rather than call for every value in view
thank you for your support
You've technically asked two questions here. One where you merge a set of values into a key-value collection, and another where you simply limit the values from a set of key-value collections and key by the ID.
Given that you're really looking for an answer to the second question, by way of your answer, here's a cleaner way of doing it:
User::select('id', 'full_name', 'email', 'job', 'password')
->get()
->keyBy('id')
->map(function($user) {
return collect($user)->except('id');
});
Related
people = {
"fruits" => {
kiwi: ["john","james","diana"],
apple: ["hibaq","nura","nadia"],
strawberry: ["hana", "valerie","india"] },
"sports" => {
rugby: ["john","james","diana"],
football: ["hibaq","nura","nadia"],
tennis: ["hana", "valerie","india"]
}
}
puts 'Enter what category to search'
category = gets.chomp
puts 'Enter what value to search for'
value = gets.chomp
people.select { |person| person[category] == value }
.each { |person| puts person["name"] }
Hi, I am new to ruby and trying to understand hashes a bit more. I want to ask the user for a category e.g "fruits" and then print the array of names that like the fruit. I am unsure how to iterate through the nested hash to access the information. Any guidance would be greatly appreciated. Thank you
Hi, I am new to ruby and trying to understand hashes a bit more. I want to ask the user for a category e.g "fruits" and then print the array of names that like the fruit. I am unsure how to iterate through the nested hash to access the information. Any guidance would be greatly appreciated. Thank you
The following should work for you.
Please note that I changed the nested hash structure to use Strings instead of Symbols in the inner hashes. Because gets returns already a string that makes it easier to get the data by the key (string) that the user entered.
people = {
"fruits" => {
"kiwi" => ["john","james","diana"],
"apple" => ["hibaq","nura","nadia"],
"strawberry" => ["hana", "valerie","india"]
},
"sports" => {
"rugby" => ["john","james","diana"],
"football" => ["hibaq","nura","nadia"],
"tennis" => ["hana", "valerie","india"]
}
}
puts 'Enter what category to search'
category = gets.chomp # when entered "sports"
puts 'Enter what value to search for'
value = gets.chomp # when entered "rudby"
p people.dig(category, value)
#=> ["john", "james", "diana"]
See Hash#dig. Other options to get data out of a Hash might be Hash#[] or Hash#fetch.
Firstly, you would make life simpler for yourself by using a consistent format when writing your hash people. I suggest
people = {
fruits: {
kiwi: ["john","james","diana"],
apple: ["hibaq","nura","nadia"],
strawberry: ["hana", "valerie","india"] },
sports: {
rugby: ["john","james","diana"],
football: ["hibaq","nura","nadia"],
tennis: ["hana", "valerie","india"]
}
}
Notice that I have written fruits: { ... rather than 'fruits' => { ... to be consistent with, for example, kiwi: [ ....
With this change we can write the following helper method which can be used for both the outer hash and the inner hashes.
def obtain_response(keys, type)
loop do
puts "Enter what #{type} to search for"
k = gets.chomp.to_sym
break k if keys.include?(k)
puts "There is no such #{type} '#{k}'. Please try again"
end
end
We may then write
category = obtain_response(people.keys, 'category')
value = obtain_response(people[category].keys, 'value')
p people[category][value]
Here is an example session.
category = obtain_response(people.keys, 'category')
Computer User
-------- ----
Enter what category to search for
colours
There is no such category 'colours'. Please try again
Enter what category to search for
sports
Now
category
#=> :sports
Next
value = obtain_response(people[category].keys, 'value')
Computer User
-------- ----
Enter what value to search for
darts
There is no such value 'darts'. Please try again
Enter what value to search for
football
Now
value
#=> :football
We may now display the desired array.
p people[category][value]
#=> ["hibaq", "nura", "nadia"]
One may of course employ more elaborate prompts, such as
Enter the category to search for ("fruits" or "sports")
I want to get the rows in a database where logged in user exists. Here is my structure
Table = Meetings
Column = Participants (stores an array of users eg.["1","2","3"]);
Auth()->id() = "1"
I want a query that will fetch rows if Auth()->id() exist in participants which stores an array of User id.
here is my code:
$meetings = Meeting::join('venues', 'meetings.meeting_venue', '=', 'venues.id')
->join('organizers','meetings.meeting_organizer','=','organizers.id')
->join('users', 'meetings.user_id','=','users.id')
->where('meetings.participants', '=', auth()->id())
->get(['meetings.*', 'venues.venue_name', 'organizers.organizer_name','users.name', ]);
Here is my participants column from the database:
array:1 [▼
0 => array:1 [▼
"participants" => array:3 [▼
0 => "52"
1 => "56"
2 => "57"
]
]
]
$meetings = DB::table('meetings')->whereJsonContains('meetings.participants', auth()->id())->get()->toArray();
dump returns empty array.
found a way around it I assigned auth()->id() to a variable then added double quote in the query. Below is how I did it
$uid = auth()->id();
-> whereJsonContains('meetings.participants', "$uid");
this works fine
You can use a trick, here it is:
$meetings = Meeting::join('venues', 'meetings.meeting_venue', '=', 'venues.id')
->join('organizers','meetings.meeting_organizer','=','organizers.id')
->join('users', 'meetings.user_id','=','users.id')
->where('meetings.participants', 'like', "%\"{auth()->id()}\"%")
->get(['meetings.*', 'venues.venue_name', 'organizers.organizer_name','users.name']);
or You can use whereJsonContains(), like so:
$meetings = Meeting::join('venues', 'meetings.meeting_venue', '=', 'venues.id')
->join('organizers','meetings.meeting_organizer','=','organizers.id')
->join('users', 'meetings.user_id','=','users.id')
-> whereJsonContains('meetings.participants', "'".auth()->id()."'")
->get(['meetings.*', 'venues.venue_name', 'organizers.organizer_name','users.name']);
Hope this helps you. Greetings
I am trying to fetch some data from my neo4j database and show in a list for auto suggestion in reactjs application. I have following codes to fetch the data.
let result = null;
try {
result = await session.run(
'MATCH (n:Person) RETURN properties(n)',
)} finally {
await session.close()
}
await driver.close()
Here the Person nodes have different properties, i.e. all the Person nodes do not have same properties. some have editor name, others have author name. What i want to do is fetching only values without keys and assigning them in an array. here
'MATCH (n:Person) RETURN properties(n)'
returns
{
"myName": "myname 1",
"hisName": "myname 2"
}
{
"herName": "myname 3",
"theirName": "myname 4"
}
And 'MATCH (n:Person) RETURN keys(n)' returns
["myName"]
["hisName"]
["herName"]
["theirName"]
But i want to fetch only values [myname 1, myname 2, myname 3, myname 4]
Could you please tell me how to fetch only values ?
Also how to keep those values in an array ?
This is how to get all values for the key myName in Person class.
Check if the node has this property using EXISTS
Put the values in an array using "COLLECT".
MATCH (n:Person)
WHERE EXISTS(n.myName)
RETURN collect(distinct n.myName)
Sample result:
["Zhen", "Praveena", "Michael", "Arya", "Karin", "Adam", "John", "mary", "jack", "david", "tom"]
This will work.
MATCH(n:Person)
RETURN apoc.coll.flatten(COLLECT(EXTRACT(key IN keys(n) | n[key])))
p.s. Sorry, EXTRACT() has been deprecated. Below is better.
MATCH(n:Shima)
RETURN apoc.coll.flatten(COLLECT([key IN keys(n) | n[key]]))
I am searching for a while now, how I could achieve to turn objects arrays into an array with only values. For example, I have an array with several Restaurants and within these restaurants there is a key named category. Category could have multiple values like Sushi, Chinese, asian. I would like to go trough all object and reduce my array from:
[{
id: '1',
title: 'Italian Dream',
category: 'Pizza, Pasta, Snack',
opening_hours: '08:00-24:00',
},
{
id: '2',
title: 'Turkish Man',
category: 'Döner, Pizza, Lahmacun',
opening_hours: '08:00-24:00',
}]
to
[ Pasta, Snack, Döner, Pizza, Lahmacun]
Would be glad if anybody could give me any advice.
Cheers
Since category is a string and not an array of strings, we need to .split(', ')
Since we have multiple categories per data item, we can use .flatMap to "combine" or flatten that what would have been an array of arrays
We can use new Set(...) to get a unique list of string values
And finally use Array.from(...) to convert the Set to an Array.
const data = [{
id: '1',
title: 'Italian Dream',
category: 'Pizza, Pasta, Snack',
opening_hours: '08:00-24:00',
},
{
id: '2',
title: 'Turkish Man',
category: 'Döner, Pizza, Lahmacun',
opening_hours: '08:00-24:00',
}
]
const categories = Array.from(new Set(data.flatMap(x => x.category.split(', '))))
console.log(categories)
You can loop your array and use split function to extract categories from your string.
let newArray = [];
oldArray.forEach(restaurant => {
newArray.push(...restaurant.category.split(', '));
});
// Here newArray contains categories with duplicate values
// You can use Set to avoid duplicate values.
newArray = [...new Set(newArray)];
I want to modify an array of hashes by a sub function, therefore I want to handover the array by reference, de-reference in the sub function and modify it furthermore.
After this modification, the array shall hold the modified values instantly, I don't want to explicitely return the modified hash (want to work on the original array).
Unfortunately I do not succeed with that. There are many web hints concerning access to references of array of hashes, but I couldn't find one which manipulates the array.
my #array_of_hashes = ( {name => "Alice"},
{name => "Bob"} );
my $myhashref = \%{$array_of_hashes[0]}; # This holds a ref to {name=>"Alice"}
my %myhash = %{$myhashref}; # De-reference, shall be the Hash to work on
print $myhash{name} . "\n"; # This shows Alice
$myhash{age}=32; # Want to add 'age' to the Alice Hash, does not work
This modified hash does not show {age}. When you have a look at #array_of_hashes with print Data::Dump::dump(#array_of_hashes) the line $myhash{age}=32; has no impact on #array_of_hashes.
How can I hand over a reference to e.g. the first element of #array_of_hashes to a function and how to I have to dereference it in the function in order to be able to modify the hash within #array_of_hashes?
You said: I want to modify an array of hashes by a sub function
If I understand right, something like the following could work:
use 5.014;
use warnings;
use Data::Dumper;
my #aoh = (
{name => "Alice"},
{name => "Bob"}
);
do_some(\#aoh); #pass arrayref
$aoh[1]->{text} = 'huhu';
say Dumper \#aoh;
say "$aoh[1]->{name} has age $aoh[1]->{age} and says $aoh[1]->{text}";
sub do_some {
my $ar = shift;
for my $hr (#$ar) { #for each array element
$hr->{age} = int rand 100;
}
}
# however (IMHO)
# using arrayref from the beginning is more cleaner
my $aohr = [
{name => "Alice"},
{name => "Bob"}
];
do_some($aohr);
$aohr->[0]->{text} = 'juju';
say Dumper $aohr;
say "$aohr->[0]->{name} has age $aohr->[0]->{age} and says $aohr->[0]->{text}";
#could use the shortened form
#say "$aohr->[0]{name} has age $aohr->[0]{age} and says $aohr->[0]{text}";
the above produces for example:
$VAR1 = [
{
'age' => 31,
'name' => 'Alice'
},
{
'age' => 10,
'text' => 'huhu',
'name' => 'Bob'
}
];
Bob has age 10 and says huhu
$VAR1 = [
{
'name' => 'Alice',
'age' => 94,
'text' => 'juju'
},
{
'name' => 'Bob',
'age' => 57
}
];
Alice has age 94 and says juju
You already created a ref to each hash when you create the array. then you defrencing the hash and allocating it to a new hash varible.
my %myhash = %{$myhashref}; # De-reference, shall be the Hash to work on
So you now have a new hash which was created as a copy of the alice hash. However the new hash and the alice hash are seperate. you then modify the new hash works ok but it will not be reflected in the alice hash as they are seperate. instead you should modify the existing hash ref. For example try below.
use strict;
use warnings;
use Data::Dumper;
my #array_of_hashes = ( {name => "Alice"},
{name => "Bob"} );
print $array_of_hashes[0]->{'name'}, "\n";#this shows alice
$array_of_hashes[0]->{'age'}=32; # Want to add 'age' to the Alice Hash, does not work
print Dumper \#array_of_hashes;