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?
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With