Smarty: How to reference to the associative array

2020-02-23 07:32发布

Array $imagelist:

Array ( 
    [additional] => Array ( 
        [count] => 2 
        [image] => Array ( 
            [nokia_e61_1.jpg] => Array ( 
                [name_body] => nokia_e61_1 
                [name_ext] => jpg 
            ) 
            [nokia_e61_2.jpg] => Array ( 
                [name_body] => nokia_e61_2 
                [name_ext] => jpg 
            ) 
            [nokia_e61_3.jpg] => Array ( 
                [name_body] => nokia_e61_3 
                [name_ext] => jpg 
            ) 
            [nokia_e61_4.jpg] => Array ( 
                [name_body] => nokia_e61_4 
                [name_ext] => jpg 
            ) 
        ) 
    ) 
    [main] => nokia_e61 
) 

The value nokia_e61_1.jpg is kept in {$getvars.imagename}.

I wrote {$imagelist.additional.image.`$getvars.imagename`.name_body} but it doesn't work.

Please help.

4条回答
等我变得足够好
2楼-- · 2020-02-23 08:06

see if {$imagelist.additional.image[$getvars.imagename].name_body} works

查看更多
等我变得足够好
3楼-- · 2020-02-23 08:09

I don't like smarty for this, nevertheless I use it. Here's extract form documentation

{$foo.$bar}   <-- display variable key value of an array, similar to PHP $foo[$bar]

To be able to do it, you have to

{assign var='key' value=$getvars.imagename}
{$imagelist.additional.image.$key.name_body}

Hope it helps

查看更多
家丑人穷心不美
4楼-- · 2020-02-23 08:20

Restructure the array, the keys for the inner 'images' offset are redundant anyway:

$imagelist = array('additional' => array('count' => 2,
       'image' => array(
            array('name_body' => 'nokia_e61_1',
                  'name_ext'  => 'jpg'),
            array('name_body' => 'nokia_e61_2',
                  'name_ext'  => 'jpg'),
            array('name_body' => 'nokia_e61_3',
                  'name_ext'  => 'jpg'),
            array('name_body' => 'nokia_e61_4',
                  'name_ext'  => 'jpg')
        )
    ),
    'main' => 'nokia_e61'
);

Gives you numerically indexed images:

array(2) {
  ["additional"]=>
  array(2) {
["count"]=>
int(2)
["image"]=>
array(4) {
  [0]=>
  array(2) {
    ["name_body"]=>
    string(11) "nokia_e61_1"
    ["name_ext"]=>
    string(3) "jpg"
  }
  [1]=>
  array(2) {
    ["name_body"]=>
    string(11) "nokia_e61_2"
    ["name_ext"]=>
    string(3) "jpg"
  }
  [2]=>
  array(2) {
    ["name_body"]=>
    string(11) "nokia_e61_3"
    ["name_ext"]=>
    string(3) "jpg"
  }
  [3]=>
  array(2) {
    ["name_body"]=>
    string(11) "nokia_e61_4"
    ["name_ext"]=>
    string(3) "jpg"
  }
}
}
["main"]=>
string(9) "nokia_e61"
}

//and then the smarty bit
{$imagelist.additional.image[0].name_body}
{$imagelist.additional.image[1].name_body}
{$imagelist.additional.image[2].name_body}
{$imagelist.additional.image[3].name_body}
查看更多
看我几分像从前
5楼-- · 2020-02-23 08:21
{php}echo $imagelist['additional']['image'][$getvars['imagename']]['name_body'];{/php}
查看更多
登录 后发表回答