Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access php array in smarty

Tags:

php

smarty

I have a object with a method like this: $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 the subarray in smarty using the $foo->getId() as index key for $array, something like:

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

also tried just:

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

But both return error:

syntax error: unidentified token 

What am i not doing right?

like image 848
amosrivera Avatar asked Mar 10 '11 16:03

amosrivera


2 Answers

You can try:

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

If this does not work, I think you have to assign the ID to an other variable beforehand:

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

In Smarty 3, this should work:

{$array.{$foo->getId()}.parent_id}
like image 64
Felix Kling Avatar answered Sep 23 '22 00:09

Felix Kling


I have just tried to get the same error as you. Funny thing is, the code runs fine. Here we go for the specs: Smarty 3.0.7 with PHP 5.3.4.

My template code:

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

The 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');

?> 

The Output:

Hello, 15
Hello, 15
like image 24
Nick Weaver Avatar answered Sep 23 '22 00:09

Nick Weaver