我正在基于数据库在 Controller 中创建一个大数组。然后在 Twig 中显示它。问题是有时候,这个数组似乎随机地被洗牌了。刷新页面后就正常了,然后又乱码了,正常的时候没有规律。
Controller 中的 PHP 数组看起来不错,没有问题。然后我将它传递给模板:
return $this->render('AcmeBundle:FooController:bar.html.twig', [
'allResults' => $results
]);
然后将其显示在 Twig 模板中:
{% for r in allResults %}
{{ r.id }} {{ r.name }}
{% endfor %}
现在发生的情况是它有时会导致页面看起来像这样:
我在 twig 模板中创建了转储以查看数组本身的样子,我得到了:
array (size=437) 'karmv>
psa' => array (size=4) ;">
'id' => string 'karmv>
psa' (length=13) ;">
'pid' => string 'lias="drapa v>zwierzat' (length=22) ;">
'pr" uct_count' => string '1' (length=1) ;">
'popularity' => string '766' (length=3) 'wor dgimna => array (size=4) ;">
'id' => string 'wor dgimna (length=18) ;">
'pid' => string 'y-ertcol-md-3" s' (length=16) ;">
'pr" uct_count' => string '1' (length=1) ;">
'popularity' => string '741' (length=3) 'gadz
elektroniczne' => array (size=4) ;">
'id' => string 'gadz
elektroniczne' (length=21) ;">
'pid' => string 'gadz
当一切正常时,它看起来像这样:
array (size=437)
'karma-dla-psa' =>
array (size=4)
'id' => string 'karma-dla-psa' (length=13)
'pid' => string 'akcesoria-dla-zwierzat' (length=22)
'product_count' => string '41' (length=1)
'popularity' => string '412' (length=3)
'worki-gimnastyczne' =>
array (size=4)
'id' => string 'worki-gimnastyczne' (length=18)
'pid' => string 'sport-dla-dzieci' (length=16)
'product_count' => string '151' (length=1)
'popularity' => string '74' (length=3)
'gadzety-elektroniczne' =>
array (size=4)
'id' => string 'gadzety-elektroniczne' (length=21)
'pid' => string 'gadzety-komputerowe' (length=19)
'product_count' => string '71' (length=2)
'popularity' => string '441' (length=3)
这是怎么回事?为什么会这样?
最佳答案
我从来没有使用过 twig 也没有读过它,但是根据我的经验,如果你从数据库中提取数据,你应该对它进行排序 order by
因为之前无法确定数据是如何排序的处理它。
一旦数组中有了数据,您就可以根据需要将其随机化。
希望对您有所帮助。
关于javascript - 阵列随机洗牌,同时在 Twig 中有约 500 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135844/