Hello people im trying to add multiple values from multiple hashes with same key.
And this is the result of scheme that I want acomplish.
HASH1 => {
'2016-07-01' => { 'val1' => '7', 'val2' => '9', },
'2016-07-02' => { 'val1' => '10', 'val2' => '6', } }
HASH2 => {
'2016-07-01' => { 'val1' => '8', 'val2' => '4', },
'2016-07-03' => { 'val1' => '3', 'val2' => '2', } }
HASH3 => {
'2016-07-01' => { 'val1' => '6', 'val2' => '5', },
'2016-07-02' => { 'val1' => '1', 'val2' => '2', },
'2016-07-04' => { 'val1' => '4', 'val2' => '2', } }
OUTPUT HASH => {
'2016-07-01' => { 'val1' => '21', 'val2' => '18', },
'2016-07-02' => { 'val1' => '11', 'val2' => '8', },
'2016-07-03' => { 'val1' => '3', 'val2' => '2', },
'2016-07-04' => { 'val1' => '4', 'val2' => '2', }, }
Im trying pushing duplicate keys to an array to identify each one, then add values.
This i'm trying is for compare 2 hashes, but i want make it for multiple hashes.
my #common = ();
foreach (keys %HASH1) {
push(#common, $_) if exists $HASH2{$_};
}
foreach my $DUP_KEY (#common){
my $v1 = $HASH1{$DUP_KEY}{'val1'} + $HASH2{$DUP_KEY}{'val1'};
my $v2 = $HASH1{$DUP_KEY}{'val2'} + $HASH2{$DUP_KEY}{'val2'};
$HASH1{$DUP_KEY}{'val1'} = $v1;
$HASH1{$DUP_KEY}{'val2'} = $v2;
}
my %OUT_HASH = (%HASH1, %HASH2);
foreach my $key (keys %OUT_HASH) {push(#ARR, $key);}
foreach (sort #ARR) {push(#ARR_CLEAN, $_);
}
but the result is not as expected, because im getting only the duplicates keys only.
someone would be so kind as to help me? thank you!
To sum up the hashes of hashes, loop over all the hashes, over their first keys (here the date), then over the second key (here the value). Sum up the numbers in a new hash.
I'd move the code to sum the values to its own sub for clarity, then pass it the references of the hashes you want to sum up.
use strict;
use warnings;
sub sum {
my %sums;
foreach my $hash (#_) {
foreach my $date (keys %{$hash}) {
foreach my $val (keys %{$$hash{$date}}) {
$sums{$date}{$val} += $$hash{$date}{$val};
}
}
}
return %sums;
}
my %HASH1 = (
'2016-07-01' => {'val1' => '7', 'val2' => '9'},
'2016-07-02' => {'val1' => '10', 'val2' => '6'}
);
my %HASH2 = (
'2016-07-01' => {'val1' => '8', 'val2' => '4'},
'2016-07-03' => {'val1' => '3', 'val2' => '2'}
);
my %HASH3 = (
'2016-07-01' => {'val1' => '6', 'val2' => '5'},
'2016-07-02' => {'val1' => '1', 'val2' => '6'},
'2016-07-04' => {'val1' => '4', 'val2' => '2'}
);
my %sums = sum(\%HASH1, \%HASH2, \%HASH3);
foreach my $date (sort keys %sums) {
print "$date\n";
foreach my $val (keys %{$sums{$date}}) {
print " $val: $sums{$date}{$val}\n";
}
}
Related
I have this category and subcategory table.
The field that has the value NULL for parent_id is a category, and the ones that use parent_id are subcategories.
My tree view has subcategories assigned only to categories, so no subcategories for subcategories.
+----+---------------------+-----------+
| id | name | parent_id |
+----+---------------------+-----------+
| 1 | Laptop | NULL |
| 2 | TV | NULL |
| 3 | Tablet & Mobile | NULL |
| 4 | PC | NULL |
| 5 | Laptops | 1 |
| 6 | Laptop accessories | 1 |
| 7 | TV accessories | 2 |
If I do a SELECT * and spice it with a while I get the following array.
'category' => [
{
'name' => 'Laptop',
'id' => '1',
'parent_id' => undef
},
{
'name' => 'TV',
'id' => '2',
'parent_id' => undef
},
{
'name' => 'Table & mobile',
'id' => '3',
'parent_id' => undef
},
{
'name' => 'PC',
'id' => '4',
'parent_id' => undef
},
{
'name' => 'Laptops',
'id' => '5',
'parent_id' => '1'
},
{
'name' => 'Laptop accessories ',
'id' => '6',
'parent_id' => '1'
},
{
'name' => 'TV accessories',
'id' => '7',
'parent_id' => '2'
}
The structure I'm looking for should look like this.
category 1
-- subcategory 1.1
-- subcategory 1.2
category 2
-- subcategory 2.1
What I get now looks like
category 1
subcategory 1.1
category 2
subcategory 1.2
subcategory 2.1
#!/usr/bin/perl
use strict;
use warnings;
my %struct = (category => [
{
'name' => 'Laptop',
'id' => '1',
'parent_id' => undef
},
{
'name' => 'TV',
'id' => '2',
'parent_id' => undef
},
{
'name' => 'Table & mobile',
'id' => '3',
'parent_id' => undef
},
{
'name' => 'PC',
'id' => '4',
'parent_id' => undef
},
{
'name' => 'Laptops',
'id' => '5',
'parent_id' => '1'
},
{
'name' => 'Laptop accessories ',
'id' => '6',
'parent_id' => '1'
},
{
'name' => 'TV accessories',
'id' => '7',
'parent_id' => '2'
}
]);
my %tree;
for my $cat (grep ! defined $_->{parent_id}, #{ $struct{category} }) {
$tree{ $cat->{id} } = $cat;
}
for my $cat (grep defined $_->{parent_id}, #{ $struct{category} }) {
$tree{ $cat->{parent_id} }{subcat}{ $cat->{id} } = $cat;
}
use Data::Dumper; print Dumper \%tree;
I'm working in Laravel. I have two arrays, and I want to insert the second array as a value in the first. For example, given
$firstArray = [
'id' => 1,
'propery_name' => 'Test Property'
];
$secondArray = [
'id' => 2,
'user_name' => 'john'
];
, I want to produce an equivalent of
$resultArray = [
'id' => 1,
'propery_name' => 'Test Property',
'userData' => [
'id' => 2,
'user_name' => 'john'
]
];
How can I achieve that?
$resultArray = $firstArray;
$resultArray['userData'] = $secondArray;
Try this:
$firstArray = ['id'=>1,'propery_name'=>'Test Property'];
$secondArray = ['id'=>2,'user_name'=>'john'];
$resultArray = ['property' => $firstArray, 'userData' => $secondArray];
Your newly created array should give you this:
{{ $resultArray['userData']['user_name'] }} = John
{{ $resultArray['property']['propery_name'] }} = Test Property
$firstArray['userData'] = $secondArray;
return $firstArray;
//result
$resultArray = [
'id' => 1,
'propery_name' => 'Test Property',
'userData' => [
'id' => 2,
'user_name' => 'john'
]
];
You can use Laravel collection class for this. Push function is best way to add values in array. https://laravel.com/docs/5.5/collections#method-put
In your case,
$firstArray = [
'id' => 1,
'propery_name' => 'Test Property'
];
$secondArray = [
'id' => 2,
'user_name' => 'john'
];
$collection = collect($firstArray);
$collection->put('userData', $secondArray);
$collection->all();
Output:
['id' => 1,
'propery_name' => 'Test Property',
'userData' => [
'id' => 2,
'user_name' => 'john'
]
];
I need to build a select drop-down list from data from find().
When I perform a recursive find:
$parlamentarios = $this->Revocatorio->Parlamentario->find('all', array('recursive' => 2));
It returns the following:
array(
(int) 0 => array(
'Parlamentario' => array(
'id' => '1',
'postulacion_id' => '4',
'created' => '2016-01-10 20:29:47',
'periodo_id' => '1',
'voto_parlamento' => '4000'
),
'Postulacion' => array(
'id' => '4',
'registro_id' => '2',
'comite_id' => '5',
'periodo_id' => '1',
'fecha_elec' => '2016-01-23',
'created' => '2016-01-03 20:40:18',
'voto' => '0',
'Registro' => array(
'id' => '2',
'cedula' => '',
'nacionalidad' => '1',
'nombre' => '',
'seg_nombre' => '',
'apellido' => '',
'seg_apellido' => '',
'genero' => true,
'fecha_nac' => '-',
'lugar_nac' => 'Portuguesa',
'fecha_reg' => '2015-12-02',
'direccion' => 'aijhaoihdwaoih',
'edad' => '21',
'foto' => '1 LOGO UNERG.jpg',
'foto_dir' => '2',
'leer' => true,
'escribir' => true,
'discapacidad' => 'ninguna',
'aptitud' => true,
'estado_civil' => 'Casado/a',
'ccregistro_id' => '0',
'name' => ' - '
),
'Comite' => array(
'id' => '5',
'comite' => 'awdawdawdawd'
),
'Periodo' => array(
'id' => '1',
'periodo' => '2015-2017'
),
'Escrutinio' => array(),
'Revocatorio' => array()
),
'Periodo' => array(
'id' => '1',
'periodo' => '2015-2017',
'Ccregistro' => array(),
'Escrutinio' => array(),
'Postulacion' => array(
(int) 0 => array(
'id' => '2',
'registro_id' => '3',
'comite_id' => '3',
'periodo_id' => '1',
'fecha_elec' => '2015-12-24',
'created' => '2015-12-22 05:42:21',
'voto' => '200'
),
(int) 1 => array(
'id' => '3',
'registro_id' => '2',
'comite_id' => '1',
'periodo_id' => '1',
'fecha_elec' => '2016-01-20',
'created' => '2016-01-03 05:46:46',
'voto' => '0'
),
(int) 2 => array(
'id' => '4',
'registro_id' => '2',
'comite_id' => '5',
'periodo_id' => '1',
'fecha_elec' => '2016-01-23',
'created' => '2016-01-03 20:40:18',
'voto' => '0'
),
(int) 3 => array(
'id' => '5',
'registro_id' => '3',
'comite_id' => '9',
'periodo_id' => '1',
'fecha_elec' => '2016-01-21',
'created' => '2016-01-03 20:41:03',
'voto' => '0'
),
(int) 4 => array(
'id' => '6',
'registro_id' => '3',
'comite_id' => '11',
'periodo_id' => '1',
'fecha_elec' => '2016-01-14',
'created' => '2016-01-03 21:06:27',
'voto' => '0'
),
(int) 5 => array(
'id' => '7',
'registro_id' => '2',
'comite_id' => '1',
'periodo_id' => '1',
'fecha_elec' => '2016-01-22',
'created' => '2016-01-04 02:38:17',
'voto' => '0'
)
)
),
'Escrutinio' => array(),
'Revocatorio' => array()
),
The relationships are:
Revocatorio hasMany Parlamentario
Parlamentario hasMany Postulacion
Postulacion hasMany Registro
I need save the id of Parlamentario, but show Postulacion.Registro.name in add view. How can I accomplish this?
Try this:
$this->Parlamentario->find("list", array(
"fields" => array("Parlamentario.id", "Postulacion.Registro.name"),
"contain" => array("Postulacion.Registro")
)
);
Peace! xD
This question already has answers here:
Push to array reference
(4 answers)
Closed 8 years ago.
In my Perl Programm, I used for testing the following static array definition:
my %data = (
56 => [
{ 'Titel' => 'Test 1',
'Subtitel' => 'Untertest 1',
'Beginn' => '00:05',
'Ende' => '00:50'
},
{ 'Titel' => 'Test 2',
'Subtitel' => 'Untertest 2',
'Beginn' => '00:50',
'Ende' => '01:40'
}
],
58 => [
{ 'Titel' => 'Test 3',
'Subtitel' => 'Untertest 3',
'Beginn' => '00:10',
'Ende' => '01:50'
}
],
51 => [
{ 'Titel' => 'Test 4',
'Subtitel' => 'Untertest 4',
'Beginn' => '00:05',
'Ende' => '00:20'
},
{ 'Titel' => 'Test 5',
'Subtitel' => 'Untertest 5',
'Beginn' => '00:20',
'Ende' => '00:40'
},
{ 'Titel' => 'Test 6',
'Subtitel' => 'Untertest 6',
'Beginn' => '00:40',
'Ende' => '01:05'
}
],
);
Now I like to change it, to get data from a database. My select returns 5 values: an id (like 56, 58 or 51 in my example) and the values for each Titel, Subtitel, Beginn and Ende.
How can I build the same array construct like in my static example?
Thanks in advance! Best regards
Daniel
Assuming you want it at the end, you need to push your hashref into the arrayref stored at $data{$id}:
push #{ $data{$id} }, {
Titel => $titel,
Subtitel => $subtitel,
Beginn => $beginn,
Ende => $ende,
};
Could be something like this. Sorry, it's been a while since I've done perl.
#!/usr/bin/perl
use Data::Dumper;
sub dataset2struc {
my $result = {};
foreach my $row (#_) {
my $id = $row->{'id'};
my $recref = $result->{$id} || ();
my #rec = #{$recref};
delete $row->{'id'};
push(\#rec, $row);
$result->{$id} = \#rec;
}
return $result;
}
my #dataset = ({"id" => 1, "a" => "b"}, {"id" => 2, "a" => "c"}, {"id" => 2, "a" => "d"});
print Dumper(dataset2struc(#dataset));
I want to group my results by countryid with the data shown below.
my #test = ();
my $st = qq[
SELECT id,countryID,abbrev
FROM myTable
];
my $q = $data->prepare($st);
$q->execute() or query_error($st);
while ( my $result = $q->fetchrow_hashref ) {
push #test, $result;
}
Using fetchrow_hashref I have no problem displayling the results
use Data::Dumper;
print STDERR Dumper(\#test);
returns
$VAR1 = [
{ 'id' => '1',
'countryID' => '1',
'title' => 'Title 1',
'abbrev' => 't1'
},
{ 'id' => '2',
'countryID' => '2',
'title' => 'Title 2',
'abbrev' => 't2'
},
{ 'id' => '3',
'countryID' => '3',
'title' => 'Title 3',
'abbrev' => 't3'
},
{ 'id' => '4',
'countryID' => '1',
'title' => 'Title 4',
'abbrev' => 't4'
}
];
I want to group it by countries as shown below.
$VAR1 = [
'countries' => {
'1' => [
{ 'id' => '1',
'title' => 'Title 1',
'abbrev' => 't1'
},
{ 'id' => '4',
'title' => 'Title 4',
'abbrev' => 't4'
}
],
'2' => [
{ 'id' => '2',
'title' => 'Title 2',
'abbrev' => 't2'
}
],
'3' => [
{ 'id' => '3',
'title' => 'Title 3',
'abbrev' => 't3'
}
]
}
];
How can I get this working in the while loop?
Ignoring the errors in your sample data structure, you are basically looking to convert form array of hashes to hash of hash of array of hashes. Once you have your initial data structure setup, you can do the following to create your new nested data structure:
for my $href ( #test ) {
my $id = $href->{countryID};
delete $href->{countryID};
push #{ $test2->{countries}{$id} }, $href;
}
Iterate each element of your array #test which basically is an array of hash references. Create a variable $id which will capture the countryID value from the hash. We delete it from the hash reference and then assign that hash reference to our new nested data structure which has countries as the first level key and the $id as the second level key.
We use push syntax to create our array of such references.
Note: As stated by thb in the comments, this does destroys your original data structure. If you'd like to retain the original structure, modify the code to the following:
for my $href ( #test ) {
my $copy = { %$href };
my $id = $copy->{countryID};
delete $copy->{countryID};
push #{ $test2->{countries}{$id} }, $copy;
}
You'll need to fix your syntax above a little (for example => instead of = >), but once you have done that, something like this should work nicely.
for (#$VAR1_orig) {
my %a = %$_;
my $countryID = $a{countryID};
delete $a{countryID};
push #{$VAR1->{countries}{$countryID}}, \%a;
}
(I have tried it on my computer, incidentally. It works.)
The above assumes that %$VAR1 is initially empty, then populates it according to #$VAR1_orig, after which you can do with $VAR1 whatever you like. (I assume that you know what %$ and #$ mean in Perl, but this is not a beginner's topic, as you may know. See man 1 perlref.)
Something like this, the input/output data structures might not be exactly what you have or want, you can patch that up.
use strict;
use Data::Dumper;
$a = [
{ 'id' => '1',
'countryID' => '1',
'title' => 'Title 1',
'abbrev' => 't1'
},
{ 'id' => '2',
'countryID' => '2',
'title' => 'Title 2',
'abbrev' => 't2'
},
{ 'id' => '3',
'countryID' => '3',
'title' => 'Title 3',
'abbrev' => 't3'
},
{ 'id' => '4',
'countryID' => '1',
'title' => 'Title 4',
'abbrev' => 't4'
}
];
my $b = {};
for my $item (#$a) {
if ( exists( $b->{ $item->{'countryID'} } ) ) {
push( #{ $b->{ $item->{'countryID'} } }, $item );
} else {
$b->{ $item->{'countryID'} } = [$item];
}
}
print Dumper($b);
The above prints:
$VAR1 = {
'1' => [
{ 'abbrev' => 't1',
'title' => 'Title 1',
'id' => '1',
'countryID' => '1'
},
{ 'abbrev' => 't4',
'title' => 'Title 4',
'id' => '4',
'countryID' => '1'
}
],
'3' => [
{ 'abbrev' => 't3',
'title' => 'Title 3',
'id' => '3',
'countryID' => '3'
}
],
'2' => [
{ 'abbrev' => 't2',
'title' => 'Title 2',
'id' => '2',
'countryID' => '2'
}
]
};