javascript - 阵列随机洗牌,同时在 Twig 中有约 500 行

标签 javascript php arrays symfony twig

我正在基于数据库在 Controller 中创建一个大数组。然后在 Twig 中显示它。问题是有时候,这个数组似乎随机地被洗牌了。刷新页面后就正常了,然后又乱码了,正常的时候没有规律。

Controller 中的 PHP 数组看起来不错,没有问题。然后我将它传递给模板:

return $this->render('AcmeBundle:FooController:bar.html.twig', [
  'allResults' => $results
]);

然后将其显示在 Twig 模板中:

{% for r in allResults %}
  {{ r.id }} {{ r.name }}
{% endfor %}

现在发生的情况是它有时会导致页面看起来像这样:

enter image description here

我在 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/

相关文章:

javascript - 如何在react中单击菜单上显示div(错误初始化前无法访问“X”)

python - Matplotlib x 轴过度拥挤的标签渲染

arrays - 有没有一种干净的方法可以在编译时声明 TBytes 兼容的值?

javascript - jquery合并所有相同的请求?

javascript - 具有相同依赖性的多个 Angular 模块用于业力测试

javascript - 我可以在 Node.js 8 中使用 ES6 模块吗?

php从序列化数据中获取满足条件的行

php - 如何使用 HTML DOM 将所有相对 URL 转换为绝对 URL?

javascript - 如何在 30 分钟后注销不活动的用户?

c - c 中的指针(初学者)