Twig 多维数组 - 无法访问值

Twig multi dimensional array - Can't access values

我有一个多维数组,但出于某种原因,我的树枝没有响应数组值。

下面是我的树枝转储

array (size=2)
  0 => 
    object(App\Models\Entities\Strategy\CriticalSuccessFactor)[5]
      private int 'csfId' => int 26
      private iterable 'kpis' => 
        array (size=1)
          0 => 
            object(App\Models\Entities\Strategy\KeyPerformanceIndicator)[10]
              ...
  1 => 
    object(App\Models\Entities\Strategy\CriticalSuccessFactor)[11]
      private int 'csfId' => int 27
      private iterable 'kpis' => 
        array (size=1)
          0 => 
            object(App\Models\Entities\Strategy\KeyPerformanceIndicator)[12]

我确实找到了这个 link,但它没有回答我的问题。

下面是我正在使用的数组数据的表示

csfs[
    private int 'csfId' => int 26
    
    'kpis' => [
        private int 'kpiId' => int 42
    
        'objectives' => [
          private int 'objectivesId' => int 40
        ]
    ] 
]

当我用 twig 输出变量时,我什么也没得到。

这是我的树枝:

{% for csf in csfs %}
    {% for kpi in csf.kpis %}
        <p> kpi ID : {{ kpi.kpiId }}</p>
    {% endfor %}
{% endfor %}

{{ csf.csfId }} 有效。它打印 ID。

我可以毫无问题地获得第一个数组值。但我无法访问 kpis 数组

twig 中的 documentation 所示,

For convenience’s sake foo.bar does the following things on the PHP layer:

check if foo is an array and bar a valid element;
if not, and if foo is an object, check that bar is a valid property;
if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
if not, and if foo is an object, check that getBar is a valid method;
if not, and if foo is an object, check that isBar is a valid method;
if not, and if foo is an object, check that hasBar is a valid method;
if not, return a null value.

Twig also supports a specific syntax for accessing items on PHP arrays, foo['bar']:

check if foo is an array and bar a valid element;
if not, return a null value.

所以你有两个选择:

  1. 调整模型CriticalSuccessFactor

您可以将方法 getKeyPerformanceIndicators 重命名为 getKpis 或添加仅引用 getKeyPerformanceIndicators

的方法 getKpis
public function getKpis() {
    return $this->getKeyPerformanceIndicators();
}
  1. 调整你的模板并直接调用方法getKeyPerformanceIndicators而不是让twig神奇地决定方法
{% for kpi in csf.getKeyPerformanceIndicators%}
   ...
{% endfor %}