Reference smarty array element by value? - arrays

Total newbie with smarty; I did try to research before asking but couldn't figure this out. My application provides me with a nested array structure like this:
custom_fields => Array (2)
0 => Array (6)
name => "key-specs"
type => "textarea"
code => "key-specs"
value => "here are some product specifications"
sd => "05/01/2013 - 09:25:44 PM"
titled => ""
1 => Array (6)
name => "key-specs-li-class"
type => "dropdownlist"
code => "key-specs-li-class"
value => "flg4_icon"
sd => "05/01/2013 - 09:25:44 PM"
titled => ""
Instead of looping through the array, I'd really like to simply reference the outer array by the "name" dimension within the inner array. For example, I know that the name "key-specs" exists somewhere in the array, and all I want to do is quickly retrieve the "value" string that resides at the same index.
Any way to do this type of direct referencing, or am I going to have to loop?

Related

How to change value in the select option of an array in the Yii2 view?

I use Yii2 Framework and I have this array filter for the 'Ordine' column:
[
'attribute' => 'Ordine',
'filterType' => GridView::FILTER_SELECT2,
'filter' => ArrayHelper::map($ordine_nome,'id','ordine'),
'filterWidgetOptions'=>['pluginOptions'=>['allowClear'=>true]],
'filterInputOptions'=>['placeholder'=>'Tutti...'],
'label' => "Ordine",
'width' => '2%',
],
Now, the array is built in this manner:
$ordini=Elenchi::find()->asArray()->orderby(['Ordine' => SORT_ASC])->all();
foreach($ordini as $l){
$ordine_nome[] = ['id'=>$l['Ordine'],'ordine'=>$l['Ordine']];
}
It's all ok. But now I want to change the value in the array select option. For example, if the value is 'OFMCap', in the array selection I want to show 'OFMCap - Ordo fratrum minorum capuccinorum'. At the moment the various selection shows only the acronim (for example OFMCap, etc....)
Anyone can help me to build this type of search?
Thank you very much, I hope to be clear.
You have mapped the same column for id and description
assuming your Elenchi models contains at least two column ordine and description
with values :
ordine description
----- -----------
OFMCap, Ordo fratrum minorum capuccinorum
so the find() return the collection of (at least) these two values
$ordini=Elenchi::find()->asArray()->orderby(['Ordine' => SORT_ASC])->all();
then you should prepare you array as
foreach($ordini as $l){
$ordine_nome[] = ['id'=>$l['ordine'],'description'=>$l['description']];
}
and you map as
'filter' => ArrayHelper::map($ordine_nome,'id','description'),
I have use lower case name for db attribure .. so manage/adapted teh case to your needs
But if you need map directly .you can wrok on array result for map()
$myMap = ArrayHelper::map($ordine_nome,'id','description'),
$myMap['OFMCap'] = 'OFMCap - Ordo fratrum minorum capuccinorum';
'filter' => $myMap,

Google GeoChart (library Lavacharts) -> AddRow / AddRows not rendering any result on map despite array of values is created

Issue:
Laravel GeoChart Library to Render Google Visualization -> AddRow / AddRows not rendering any result on map despite array of values is created.
Controller Code (chart creation code)
$countryIso = ['US','CA','BR'];
foreach ($countryIso as $isocode) {
$productDDP[$isocode] = $this->product->priceCalc($product = $product, $countryIso = $isocode);
}
View Results: using different variants of Code and giving errors:
If I print the result of print_r($productDDP);
it displays the following code:
Array
(
[US] => 900
[CA] => 1,276
[BR] => 1,215
)
I tried different approaches:
with ->addRows(array($productDDP));
"Invalid number of cells, must be less than or equal to the number of columns."
with ->addRow(array($productDDP)); or using ->addRow([$productDDP]);
Argument 3 passed to Khill\Lavacharts\DataTables\Cells\Cell::__construct() must be of the type array, string given
with ->addRows($productDDP);
Argument 1 passed to Khill\Lavacharts\DataTables\DataTable::addRow() must be of the type array or null, string given
with ->addRow(array([$productDDP]))
Render the chart but no value is set on the map.
Questions?
- What I have to use for that kind of arrays?
- addRow or addRows?.
- In which format do we have to pass array data for addRow/s?
Taking into consideration I passed all possible variants to addrow() I don't know if its an issue or a coding problem.
any help appreciated.
the array is in the wrong format
first, you're creating a single array, with key / value pairs
Array
(
[US] => 900
[CA] => 1,276
[BR] => 1,215
)
each row should be an array with two values, no key value pairs
something like...
Array
(
[0] => Array
(
[0] => US
[1] => 900
)
[1] => Array
(
[0] => CA
[1] => 1276
)
[2] => Array
(
[0] => BR
[1] => 1215
)
)
try building the arrays like this...
$countryIso = ['US','CA','BR'];
$productDDP = [];
foreach ($countryIso as $isocode) {
$productDDP[] = array($isocode, $this->product->priceCalc($product = $product, $countryIso = $isocode));
}
then use addRows
addRows($productDDP);

Access an array item that is an anonymous hash in Template Toolkit in Perl

I have this piece of code as part of a foreach loop in my controller:
my $gr = My::Model::Group->new(id => $gra->gr_id);
$gra = My::Model::Group::Admin->new(id => $gra->id);
push(#$groups, {$gr => $gra});
In #$groups array I want to store anonymous hashes where the key element is the group object and the value element is the admin of that group object. Then in the template I want to show the list of different groups that the admin can log in, for that I have this code:
[%- FOREACH gr IN groups -%]
<li><input type="radio" name="group" value="[% gr.id %]">[% gr.name %]</input></li>
[%- END -%]
I know that the p IN partners is not right but is to show you what I want to achieve. Any suggestions on the template code?
duskwuff already explains in their answer that you can't use objects as hash keys as they get serialized and you'll lose the object-ness. My answer builds on that.
Let's say you have an array of arrays instead, where each inner array holds a pair of objects. I've created Moo classes to illustrate.
package My::Model::Group;
use Moo;
has [qw/id name/] => ( is => 'ro' );
package My::Model::Group::Admin;
use Moo;
has [qw/id name/] => ( is => 'ro' );
package main;
my $groups = [
[
My::Model::Group->new( id => 1, name => 'group1' ) =>
My::Model::Group::Admin->new( id => 1, name => 'foo' )
],
[
My::Model::Group->new( id => 2, name => 'group2' ) =>
My::Model::Group::Admin->new( id => 1, name => 'foo' )
],
[
My::Model::Group->new( id => 3, name => 'group3' ) =>
My::Model::Group::Admin->new( id => 1, name => 'bar' )
],
[
My::Model::Group->new( id => 4, name => 'group4' ) =>
My::Model::Group::Admin->new( id => 1, name => 'foo' )
],
];
There are four pairs. Two admins, four groups. Three of the groups belong to the foo admin, and one to bar. Now let's look at the template.
use Template;
my $tt = Template->new();
$tt->process( \*DATA, { groups => $groups }, \my $output )
or die $tt->error;
print $output;
__DATA__
[%- FOREACH item IN groups -%]
[%- DEFAULT by_admin.${item.1.name} = [] -%]
[%- by_admin.${item.1.name}.push(item.0) -%]
[%- END -%]
[%- FOREACH admin IN by_admin.keys.sort -%]
[%- FOREACH group IN by_admin.$admin -%]
[%- admin %] -> [% group.id %]
[%- END -%]
[%- END -%]
The relevant part obviously is the DATA section. We need to reorganize the array data structure into a hash that has the admins, and then each group sorted into one of the admin slots.
We don't need to create the by_admin variable. It will be created globally implicitly. But we do need to set a default value for $by_admin->{$item[0]->name} (I'm using Perl syntax now, to make it easier to understand). It seems like Template Toolkit does not know autovivification, and the DEFAULT keyword is similar to the //= assignment operator in Perl.
We can then push the first element of item into the array ref we just created (if it didn't exist yet) inside the hash ref element with the key item.1.name inside by_name.
Once we're done preparing, the rest is just a simple loop. We iterate the sorted keys of by_admin, and then iterate the array ref that's behind that key.
Here's the output:
bar -> 3
foo -> 1
foo -> 2
foo -> 4
It would make sense to do the preprocessing not in a template, but in your controller instead. As normal Perl code it should be easier to read.
my %by_admin;
for my $group (#$groups) {
push #{ $by_admin{ $group->[1]{name} } }, $group->[0];
}
Note that I have omitted use strict and use warnings for brevity.
You will need to rework your code significantly to make this possible.
Keys in Perl hashes are strings, not scalars. Using anything that isn't a string as a key in a hash (e.g, $gr in the expression { $gr => $gra } will cause it to be stringified, just as if you had interpolated it into a string or printed it. Unless you have explicitly overloaded the "" operator on the My::Model::Group object, the key will end up being stored as a literal string along the lines of:
"My::Model::Group=HASH(0x1234567890)"
This string cannot be converted back to the original object -- in fact, the original object was probably garbage-collected as soon as it went out of scope, so it no longer exists at all.
Consider storing the pair as an array reference instead, e.g.
push #$groups, [$gr, $gra];

Difficulties initializing an array in Perl

I have the following code:
print Dumper($dec_res->{repositories}[0]);
print Dumper($dec_res->{repositories}[1]);
my #repos = ($dec_res->{repositories});
print scalar #repos . "\n";
and the output is the following:
$VAR1 = {
'status' => 'OK',
'name' => 'apir',
'svnUrl' => 'https://url.whatever/svn/apir',
'id' => 39,
'viewvcUrl' => 'https://url.whatever/viewvc/apir/'
};
$VAR1 = {
'status' => 'OK',
'name' => 'CCDS',
'svnUrl' => 'https://url.whatever/svn/CCDS',
'id' => 26,
'viewvcUrl' => 'https://url.whatever/viewvc/CCDS/'
};
1
So my question is why $dec_res->{repositories} is clearly an array but #repos is not?
Here I printed the size but even trying to access elements with $repos[0] still returns an error.
Dumping $repos[0] actually print the whole structure... like dumping $dec_res->{repositories}
$dec_res->{repositories} is clearly an array
It isn't. It is an array reference.
but #repos is not?
It is an array.
You are creating a list that is one item long, and that item is the array reference. You then assign the list to the array, so the array holds that single item.
You need to dereference the array instead.
my #repos = #{$dec_res->{repositories}};
perlref explains more about references in Perl.

Laravel 4 updating all records with array gives me parameter mismatch error

Trying to update each row of a table with a multidimensional array created from querying another database.
The array:
Array
(
[0] => Array
(
[community_id] => ap
[floorplan_code] => ap1-1a
[name] => 33flat
[hidden] => 0
)
[1] => Array
(
[community_id] => ap...
Here is the code I'm using in an attempt to update:
$floorPlan = new Floorplan; //create new instance
$floorPlan->get(); //get all rows
$floorPlan->update($floorplanMappedArray); //map db columns to array and update
Error message: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array.
The parameter mismatch came from the fact that I was trying to shove a multidimensional array into a single row. Therefore, I needed a foreach loop to index through the multidimensional array.
I thought that there was a magical way to use the update() method in the same way that the insert() method is used. Apparently, there is not.
Here is the code that solved the parameter mismatch error:
foreach ($floorplanMappedArray as $floorPlan) {
Floorplan::where('floorplan_code', $floorPlan['floorplan_code'])->update($floorPlan);
}

Resources