Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在smarty中访问php数组_Php_Smarty - Fatal编程技术网

在smarty中访问php数组

在smarty中访问php数组,php,smarty,Php,Smarty,我有一个对象,其方法如下:$foo->getId(),它返回一个整数,我有一个数组,如下所示: $array( 1=> array( "parent_id" => 14 ), 2=> array( "parent_id" => 15 ) ); 我需要使用$foo->getId()作为$array的索引键,在smarty中访问子数组中的parent\u id,类似于: {$array[

我有一个对象,其方法如下:
$foo->getId()
,它返回一个
整数
,我有一个数组,如下所示:

$array(
     1=> array(
            "parent_id" => 14
     ),
     2=> array(
            "parent_id" => 15
     )
);
我需要使用
$foo->getId()
作为
$array
的索引键,在smarty中访问子数组中的
parent\u id
,类似于:

{$array[$foo->getId()].parent_id}
我也试过:

{$array[$foo->getId()]}
但两者都返回错误:

syntax error: unidentified token 
我做得不对的是什么

试试这个:

$array[$foo->getId()]["parent_id"]
您可以尝试:

{$array.$foo->getId().parent_id}
如果这不起作用,我认为您必须事先将ID分配给其他变量:

{assign var=foo_id value=`$foo->getId()`}{$array.$foo_id.parent_id}
在Smarty 3中,这应该是可行的:

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

我刚刚试着得到和你一样的错误。有趣的是,代码运行良好。我们来看看规范:Smarty 3.0.7和PHP5.3.4

我的模板代码:

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

首先,不要忘记将两个变量传递给Smarty

$smarty->assign('array', $array);
$smarty->assign('foo', $foo);
并且,在Smarty模板中,使用:

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

从未使用过smarty,但在PHP中您可以:

<?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

试试这个。从php文件将对象分配给smarty变量“foo”

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

我将这样使用一个变量:

$a=array(
     1 => array(
            "parent_id" => 14
     ),
     2 => array(
            "parent_id" => 15
     )
);
然后,您可以按如下方式访问阵列:

$a[1]["parent_id"]

可能必须使用
{php}{/php}
才能使用
$foo->getId()
哪个版本的smarty?我在没有
{php}
的其他部分中使用
{foo->getId()}
,所以我知道它是有效的,我不确定这个版本应该是最新的,让我检查一下。@amosrivera,但这并不一定意味着可以将其用作数组索引。当然,我不知道这正是我问的原因。或者干脆换成Twig。尽管速度更快,并且具有模板继承等更有用的功能,但它也允许您在此处尝试执行的操作:
{array[foo.id].parent_id}}
(或者如果您需要显式方法调用:
{array[foo.getId()].parent_id}
)也可以在
条件下工作,如果有人来到这里需要它;-)
{assign var="val" value=$foo->getId()}
{$arr.$val.parent_id}
$a=array(
     1 => array(
            "parent_id" => 14
     ),
     2 => array(
            "parent_id" => 15
     )
);
$a[1]["parent_id"]