smarty get offset of array - arrays

I have some trouble in prestashop 1.6 using smarty.
I have an array, but its offset are not reset for each product.
so for the firdst product, with attrivute it has offset 1,2,3,4 Then for the next product it has offest 5,6,7,8 etc.
I have that kind of array
$combinations Smarty_Variable Object (3)
->value = Array (4)
5 => Array (14)
attributes_values => Array (1)
1 => "S"
attributes => Array (1)
0 => 1
price => 0
specific_price => Array (0)
ecotax => 0
weight => 0
quantity => 20
reference => ""
unit_impact => 0
minimal_quantity => "1"
date_formatted => ""
available_date => ""
id_image => -1
list => "'1'"
6 => Array (14)
I try to go trhough this array but it does not work when I put empty offset (it is inside a foreach)
{$combinations[]['quantity']}
How can I tell him to go trhough the first iteration, and then in the second automatically ?
This return to me the following errors.
Fatal error: Cannot use [] for reading in /htdocs/tools/smarty/sysplugins/smarty_internal_templatebase.php(157) : eval()'d code on line 584
I can not tell him which offset to use, because for each product it goes up and is not reset to 0.
I would be very gratefull for anykind of help.

Here's how to do it, current return the first value of an array
{$combination = current($combinations)}
{$combination['quantity']}

in addition to #UnLoCo answer, if you need these keys 1,2 ... 7,8
{foreach from=$array key=key item=value}
{$key} => {$value}
{/foreach}
or
{foreach $array $key=>$value} {* like PHP style *}
{$key} => {$value}
{/foreach}
Also Smarty docs may help you http://www.smarty.net/docs/en/language.function.foreach.tpl

Related

putting a hash value into an array in ruby

I am trying to insert a list of account numbers into an array from an json return, I turned the json return into an hash, but I cannot for some reason insert the values into an array. I checked the hash locations on irb, and it gets the account number, for an example the location my_hash["aws_accounts"][0]["owner_id"] will get me the first account number and my_hash["aws_accounts"][0]["status"]["level"] will get me the status of the first account.
I essentially want to iterate through all the accounts and store the account number if its respective status color is "yellow".
HERE IS MY CODE:
require 'json'
require 'rest-client'
j = RestClient.get 'https://chapi.cloudhealthtech.com/v1/aws_accounts?api_key=###&page=1&per_page=100'
my_hash = JSON.parse(j)
accnt_size = my_hash["aws_accounts"].size
intaccntsize = accnt_size.to_i
account_number_array = Array.new
x = 0
for accnt_iteration in x..intaccntsize do
puts accnt_iteration
if my_hash["aws_accounts"][accnt_iteration]["status"]["level"] == "yellow"
account_number_array.push(my_hash["aws_accounts"][accnt_iteration]["owner_id"])
end
end
HERE IS THE ERROR MESSAGE
in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
from C:/Users/----/Desktop/-----/ruby_aws_sdk.rb:12:in `each'
from C:/Users/------/Desktop/-------/ruby_aws_sdk.rb:12:in `<main>'
any suggestions will help. thanks.
The actual solution to your problem is to use the 3 dot range instead of 2 dot (3 dots is end-exclusive and 2 dots is end-inclusive) as seen in the following (this uses the same my_hash as my second code block below):
for x in 0..my_hash["aws_accounts"].size do
puts x
end
# 0
# 1
# 2
=> 0..2
my_hash["aws_accounts"][2]
=> nil
for x in 0...my_hash["aws_accounts"].size do
puts x
end
# 0
# 1
=> 0...2
my_hash["aws_accounts"][1]
=> {"owner_id"=>2, "status"=>{"level"=>"orange"}}
Instead of getting the number of accounts and trying to access them through their index, I would just iterate over the accounts on their own. Here's a quick sample, with what I believe (based on your description) are the relevant pieces of my_hash and your expected output.
my_hash = {
"aws_accounts" => [
{ "owner_id" => 1, "status" => { "level" => "yellow" } },
{ "owner_id" => 2, "status" => { "level" => "orange" } }
]
}
account_number_array = []
my_hash["aws_accounts"].each do |account|
if account["status"]["level"] == "yellow"
account_number_array << account["owner_id"]
end
end
puts account_number_array.inspect
# => [1]

Cakephp Hash combine concatenate two fields

How can I concatenate two fields inside a select box using cakephp 2.5 and Hash:combine ?
Today I have name:
$banks = Hash::combine($banks, '{n}.Bank.id', '{n}.Bank.name');
I need name and identifier, I tried this:
$banks = Hash::combine($banks, '{n}.Bank.id', '{n}.Bank.name {n}.Bank.identifier');
But it return NULL.
How can I have : name - identifier ?
Also try to concatenate the two fields at the model but could not add an hiffen between name and identifier.
You can provide array’s for both $keyPath and $valuePath. If you do this, the first value will be used as a format string, for values extracted by the other paths:
$result = Hash::combine(
$a,
'{n}.User.id',
array('%s: %s', '{n}.User.Data.user', '{n}.User.Data.name'),
'{n}.User.group_id'
);
/* $result now looks like:
Array
(
[1] => Array
(
[2] => mariano.iglesias: Mariano Iglesias
)
[2] => Array
(
[14] => phpnut: Larry E. Masters
)
)
*/
$result = Hash::combine(
$a,
array('%s: %s', '{n}.User.Data.user', '{n}.User.Data.name'),
'{n}.User.id'
);
/* $result now looks like:
Array
(
[mariano.iglesias: Mariano Iglesias] => 2
[phpnut: Larry E. Masters] => 14
)
*/
See CookBook > Hash for mode details.

CakePHP3.4: Why Request::getHeader() returns an array?

I have the following request:
2017-04-05 06:53:31 Error: Cake\Http\ServerRequest Object
(
...
[_environment:protected] => Array
(
[HTTP_REGISTRATION] => eur73_9lhfQ:...SJMryPxCNzKcqSufdpFMOaux
...
)
[_detectorCache:protected] => Array
(
[ajax] =>
[get] => 1
[head] =>
[options] =>
[post] =>
)
[uri:protected] => Zend\Diactoros\Uri Object
(
[allowedSchemes:protected] => Array
(
[http] => 80
[https] => 443
)
...
)
...
)
$this->request->header['registration'] returns:
eur73_9lhfQ:...SJMryPxCNzKcqSufdpFMOaux
as string
$this->request->getHeader('registration') returns:
[Registration] => Array
(
[0] => eur73_9lhfQ:...SJMryPxCNzKcqSufdpFMOaux
)
Why does it return an array?
The HTTP standard allows multiple headers with the same field name to be present in case all values of that header can be expressed as a single, comma separated string (Set-Cookie is an exception to that rule, it cannot express multiple values in a single string, but in practice does still appear multiple times in order to define multiple cookies).
In order to support this in a convenient way, the PSR-7 standard (which \Cake\Http\ServerRequest complies to) defines the getHeader() method to return header values as arrays. The complement to that is the getHeaderLine() method, which is ment to return multiple values as a single, comma separated string.
See also
https://www.rfc-editor.org/rfc/rfc7230#section-3.2.2
http://www.php-fig.org/psr/psr-7/#headers-with-multiple-values

Perl: array and hash

Further to finding an answer to my earlier question Perl: slicing an array of hashes, I am stuck again and unable to see what I have done wrong.
What I have is
Array( Array0(Hash0,Hash1),Array1(Hash0,Hash1),Array2(Hash0,Hash1)...)
use strict;
use warnings;
my #DDs = ();
my #Ds = ();
my %hsh = ();
my %dot1 = ( 'x' => 1, 'y' => 2, 'r' => 3 );
my %dot2 = ( 'x' => 4, 'y' => 5, 'r' => 6 );
my %dot3 = ( 'x' => 7, 'y' => 8, 'r' => 9 );
my %dot4 = ( 'x' => 1.1, 'y' => 1.2, 'r' => 1.3 );
my %dot5 = ( 'x' => 2.1, 'y' => 2.2, 'r' => 2.3 );
my %dot6 = ( 'x' => 3.1, 'y' => 3.2, 'r' => 3.3 );
my %dot7 = ( 'x' => 4.1, 'y' => 4.2, 'r' => 4.3 );
my %dot8 = ( 'x' => 5.1, 'y' => 5.2, 'r' => 5.3 );
my #dotsA = ( \%dot1, \%dot2 );
my #dotsB = ( \%dot3, \%dot4 );
my #dotsC = ( \%dot5, \%dot6 );
my #dotsD = ( \%dot7, \%dot8 );
my %Ds = ( \#dotsA, \#dotsB, \#dotsC, \#dotsD );
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
###"Can't use an undefined value as HASH reference" error here
%hsh = %{ $DDs[0] }; #expect %dot3
print scalar #DDs, "\n"; #expect 2 but has value of 1
print $hsh{'x'}, "\n";
Reference found where even-sized list expected at /Users/schwern/tmp/test.plx line 10.
Line 10 is this:
my %dot1 = {'x'=>1,'y'=>2,'r'=>3};
This is Perl's cryptic way of saying you fed a hash reference to a hash. Perl, unfortunately, distinguishes very strongly between things and references to that thing.
%dot1 is a hash. It takes a list and turns it into a hash. A list like ( x => 1, y => 2, r => 3). { x => 1, y => 2, r => 3 } creates a hash reference. That's a single thing, a scalar. It's like saying my %dot1 = (42). It doesn't make any sense.
%dot1 is a hash, it wants a list like (x => 1, y => 2)
$dot1 is a scalar, it can store a hash reference like { x => 1, y => 2 }.
my %Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
A hash requires a key and a value, pairs. last_name => "Schwern". When you give it a bunch of array references like that, it will read them as key1, value1, key2, value2... but what is it using as the key? It's using the stringification of that reference, something like ARRAY(0x7fb721800468).
If you asked for $D{\#dotsA} you'll get back a reference to #dotsB. You will not be able to get #dotsA back, a Perl hash key is just a string, not a reference.
This isn't a very good way to store an array in a hash. I'm not sure what you're trying to accomplish, but you probably want to reference them by name.
# A hash of lists.
my %Ds = ( A => \#dotsA, B => \#dotsB, C => \#dotsC, D => \#dotsD );
# Get back a reference to #dotsA.
my $dotsA = $Ds{A};
But looking at the following code, #DDs = $Ds[1];, I think you meant to initialize #Ds instead of %Ds.
#Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
And now the following works... sort of. More later.
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
Unlike in PHP, hashes and arrays are totally different things. my #Ds and my %Ds declare totally different variables. It doesn't help that you access them both with $Ds. In Perl5, the sigil indicates what's going to get returned. $Ds[1] and $Ds{foo} both use $Ds because they're returning a scalar. #Ds[1,2] and #Ds{(foo, bar)} use #Ds because they're returning a list (known as a slice). Confusing, but that's how it works.
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
You're not getting #dotsB, you're getting a reference to #dotsB. All complex data structures in Perl store references, not the actual value. This is like $DDs[0] = \#dotsB. If you want to get the actual value you have to dereference it.
#DDs = #{$Ds[1]}; # Now #DDs has a copy of #dotsB
And finally it works.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10; # for say()
my %dot1 = ('x'=>1,'y'=>2,'r'=>3);
my %dot2 = ('x'=>4,'y'=>5,'r'=>6);
my %dot3 = ('x'=>7,'y'=>8,'r'=>9);
my %dot4 = ('x'=>1.1,'y'=>1.2,'r'=>1.3);
my %dot5 = ('x'=>2.1,'y'=>2.2,'r'=>2.3);
my %dot6 = ('x'=>3.1,'y'=>3.2,'r'=>3.3);
my %dot7 = ('x'=>4.1,'y'=>4.2,'r'=>4.3);
my %dot8 = ('x'=>5.1,'y'=>5.2,'r'=>5.3);
my #dotsA = (\%dot1,\%dot2);
my #dotsB = (\%dot3,\%dot4);
my #dotsC = (\%dot5,\%dot6);
my #dotsD = (\%dot7,\%dot8);
my #Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
my #DDs = #{$Ds[1]}; #expect #dotsB
my %hsh = %{$DDs[0]}; #expect %dot3
say scalar #DDs; #expect 2
say $hsh{'x'};
I would also advise that you get comfortable working directly with references since that's what complex data structures are: references. Converting back and forth from references to values is confusing. Working with references is one less thing to convert in your code, in your head, and less copying done in your program.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10; # for say()
my $dot1 = {'x'=>1,'y'=>2,'r'=>3};
my $dot2 = {'x'=>4,'y'=>5,'r'=>6};
my $dot3 = {'x'=>7,'y'=>8,'r'=>9};
my $dot4 = {'x'=>1.1,'y'=>1.2,'r'=>1.3};
my $dot5 = {'x'=>2.1,'y'=>2.2,'r'=>2.3};
my $dot6 = {'x'=>3.1,'y'=>3.2,'r'=>3.3};
my $dot7 = {'x'=>4.1,'y'=>4.2,'r'=>4.3};
my $dot8 = {'x'=>5.1,'y'=>5.2,'r'=>5.3};
my $dotsA = [$dot1,$dot2];
my $dotsB = [$dot3,$dot4];
my $dotsC = [$dot5,$dot6];
my $dotsD = [$dot7,$dot8];
my $Ds = [$dotsA,$dotsB,$dotsC,$dotsD];
my $DDs = $Ds->[1]; #expect $dotsB
my $hsh = $DDs->[0]; #expect $dot3
say scalar #$DDs; #expect 2
say $hsh->{'x'};
You should review perlreftut and the Nested Data Structures chapter of Modern Perl.

Yii2 Array sorting

In my Yii2 Project I have an array for example
$array = [];
$array [] = 8 , 3, 6
So when I print out the array is
[8,3,6]
So when I use the same in a where statement it jumbles up.
$class = ModelClass::find()->where(['array_no' => $array])->all
So when I print out class I get the output in asc order sorted..
I get the information of
3 in the first
6 in the second place
8 in the third place.
How can i stop this from happening. I want them to return my output in the same order as array
You should use ORDER BY FIELD(), e.g. :
$models = ModelClass::find()
->where(['array_no' => $array])
->orderBy(new \yii\db\Expression('FIELD (array_no, '.implode(',', $array).')'))
->all();

Resources