Access to php array in smarty

I have an object with this method: $foo->getId() , which returns an integer , and I have an array like:

 $array( 1=> array( "parent_id" => 14 ), 2=> array( "parent_id" => 15 ) ); 

I need to access parent_id inside a subarray in smarty, using $foo->getId() as an index key for $array , something like:

 {$array[$foo->getId()].parent_id} 

also tried just:

 {$array[$foo->getId()]} 

But also the reverse error:

 syntax error: unidentified token 

What am I not doing right?

+4
source share
7 answers

You can try:

 {$array.$foo->getId().parent_id} 

If this does not work, I think you need to assign an ID to another variable in advance:

 {assign var=foo_id value=`$foo->getId()`}{$array.$foo_id.parent_id} 

In Smarty 3, this should work:

 {$array.{$foo->getId()}.parent_id} 
+7
source

I just tried to get the same error as you. Funny, the code is working fine. Here we look at the specifications: Smarty 3.0.7 with PHP 5.3.4.

My template code is:

 <html> <head> <title>Smarty</title> </head> <body> Hello, {$array[2]["parent_id"]}<br/> Hello, {$array[$foo->getId()]["parent_id"]}<br/> </body> </html> 

Php file:

 <?php class Foo { public function getId() { return 2; } } // ... smarty config left out ... $smarty has been assigned successfully $foo = new Foo(); $array = array( 1 => array("parent_id" => 14), 2 => array("parent_id" => 15) ); $smarty->assign('array', $array); $smarty->assign('foo', $foo); $smarty->display('index.tpl'); ?> 

Output:

 Hello, 15 Hello, 15 
+3
source

Try the following:

 $array[$foo->getId()]["parent_id"] 
+1
source

I will use the variable this way:

 $a=array( 1 => array( "parent_id" => 14 ), 2 => array( "parent_id" => 15 ) ); 

Then you can access your array as follows:

 $a[1]["parent_id"] 
+1
source

First, don't forget to pass tow variables to Smarty

 $smarty->assign('array', $array); $smarty->assign('foo', $foo); 

And in your Smarty template use:

 {$array[$foo->getId()]["parent_id"]} 
0
source

Never used smarty, but in PHP you can do:

 <?php class foo { public function getId() { return (int)2; } } $array = array( 1 => array( "parent_id" => 14 ), 2 => array( "parent_id" => 15 ) ); $foo = new Foo; echo $array[(int)$foo->getId()]['parent_id']; //15 

I have a type cast as an integer (int)$foo->getID() , because the $array indices are integers, enclosing them in brackets {} type castes them in strings.

(Maybe you should look at Foo::getID() and see if the string returns)

In smarty, then you can do something like this (theoretically, since I cannot check it in smarty):

 {$array[(int)$foo->getId()]['parent_id']} //Also check if this works, but I suspect it shouldn't (the syntax it not valid PHP) {$array.(int)$foo->getId().parent_id} 
0
source

Try it. From the php file, assign the object to the smarty variable 'foo'

 {assign var="val" value=$foo->getId()} {$arr.$val.parent_id} 
0
source

Source: https://habr.com/ru/post/1343203/


All Articles