2017-09-10 16 views
0

DATAS如何使用動態可變

$datas = [ 
    'first' => [ 
     1 => [ 
      'count' => 20 
     ], 
     2 => [ 
      'count' => 100 
     ] 
    ] 
]; 

我已經從數據庫中的另一個數據負載打印值,其結果是這樣的:

$rows = [ 
    1 => 'aaaa', 
    2 => 'bbbb' 
]; 

我環在視圖中的行

{% for key, row in rows %} 
    {{ datas.first.key.count }} // empty 
{% endfor %} 

我想使用行鍵顯示數據計數,但它不工作,datas.first.1。計數打印正確的結果

在PHP

$datas = [ 
    'first' => [ 
     1 => [ 
      'count' => 20 
     ], 
     2 => [ 
      'count' => 100 
     ] 
    ] 
]; 

$rows = [ 
    1 => 'aaaa', 
    2 => 'bbbb' 
]; 

foreach ($rows as $key => $value) { 
    echo 'count is :'.$datas['first'][$key]['count']; 
} 

這是我覺得(不是很清楚),你想這樣做的PHP

樣品

回答

0

{% for row in datas.first %} 
    {{ row.count }} // count value 
{% endfor %} 

這裏是一個工作twigfiddle:

https://twigfiddle.com/6yup1l

+0

感謝您的回答,但它不是動態的,我舉了一個例子到文章 – Chan

+0

我不確定你的意思是什麼部分是動態的?在Twig中,你可以使用[IF語句](https://twig.symfony.com/doc/2.x/tags/if.html),然後檢查你的數組是否包含'first',然後執行一些操作。你的第二個例子只顯示'$'和'1'和'2'鍵。 –

+0

關鍵是動態的,這個示例只有兩個數據,在現實世界中可能超過30個數據,我不能使用if語句 – Chan