2

I have modified the code from this question but I'm running into an issue.

{% set allCats = craft.categories.group('blogCategories').level(1).find() %}

{% set catArray = {} %}

{% for cat in allCats %}

    {% set catArray = catArray | merge({(cat.id):craft.entries.relatedTo(cat).total() }) %}

{% endfor %}

{% set catArray = catArray|sort|reverse %}

{% for catId, count in catArray %}

    {% set category = craft.categories.id(catId).first() %}

    <li>
        <a href="{{ category.url }}">{{ category.title }} <span>{{count}}</span></a>
    </li>

{% endfor %}

Ive ran a dump on the catArray array and the category id isnt being set as the key, regardless of if I try put brackets around it to protect it, I only get the value in the array.

7
  • Did you try the code that I provided (totally untested from my side) in this other Q/A? Ohh and I think we should better close this thread here and "discuss" your problems over there...
    – carlcs
    Commented Jul 30, 2014 at 20:12
  • possible duplicate of Order tags by count - e.g. Top 10 Tags Used
    – carlcs
    Commented Jul 30, 2014 at 20:12
  • Sean, I wonder why I (and you too) put the cat.id in brackets? Actually no reason to do this..
    – carlcs
    Commented Jul 30, 2014 at 20:20
  • I don't think it's identical. The context is different and the issue I have hasn't been mentioned there. The reason you (and therefore I) have it in parentheses is due to how Twig treats keys. It does work when I use a category.slug as a key, but category.id does not want to work. Commented Jul 30, 2014 at 20:27
  • Yes not really completely a duplicate, but if you are running into problems those exact problems are laying in that other Q/A, too.
    – carlcs
    Commented Jul 30, 2014 at 20:30

1 Answer 1

2

If you encounter problems with assigning variables as the keys, what about putting all your values into objects?

{% set catObjects = [] %}

{% for cat in allCats %}

    {% set catObject = [
        { catId: cat.id, catCount: craft.entries.relatedTo(cat).total()  }
    ] %}

    {% set catObjects = catObjects|merge(catObject) %}

{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.