Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array randomly shuffles while having ~ 500 rows in twig

I am creating one big array in controller, based on the database. Then in twig I display it. The problem is that sometimes, randomly, this array seems to be shuffled. After I refresh the page it's normal, but then again it's shuffled, there's no pattern for when it is normal.

PHP array in the controller looks good, there's no problem with it. Then I pass it to the template:

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

And then display it inside twig template:

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

What happens now is that it sometimes causes the page to look like this:

enter image description here

I created dump inside twig template to see what the array itself looks like, and I got:

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   

While when it's ok it looks like this:

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)

What's going on? Why does that happen?

like image 216
khernik Avatar asked Jan 25 '15 11:01

khernik


Video Answer


1 Answers

I never use twig yet or read about it, but from my experience if your extracting data from DB, you should have it sorted order by as there is no certainty on how the data is sorted before processing it.

Once you have the data in the array, you can then randomized it as needed.

Hope this helps a bit.

like image 168
Nick Ace Avatar answered Sep 30 '22 17:09

Nick Ace