<p>Try something like:</p>

<pre><code>{% set breadGroups = entry.breads | group('bread.first.id') %}

{% for breadId, blocks in breadGroups %}

    {% set sum = 0 %}

    {% for block in blocks %}

        {% set sum = sum + block.quantity %}

    {% endfor %}

    Total qty for Bread ID {{ breadId }}: {{ sum }}

 {% endfor %}
</code></pre>

<p>The <code>group</code> filter consumes a list &mdash; in this base, an array of Matrix blocks &mdash; and produces an array of arrays where the <em>key</em> is the grouping parameter, and the <em>value</em> is an array of items from the original list for which the group criteria matches the key.</p>

<p><em>c.f.</em> Craft docs: <a href="http://buildwithcraft.com/docs/templating/filters#group" rel="noreferrer">http://buildwithcraft.com/docs/templating/filters#group</a></p>

CC BY-SA 3.0
2015-09-07T18:11:29.997Z
2015-09-07T18:11:29.997Z
Michael Rog
<p>This is the setup: </p>

<p>I have a Matrix field called Breads. There is 1 block called Bread.</p>

<p>Within, I have two fields:</p>

<ul>
<li>An Entries field called Selected bread (limited to 1 entry)</li>
<li>A Number field called Quantity.</li>
</ul>

<p>Lets say I have 3 rows. Row 1 and 3 have the same entry selected, but different quantities. Is there a way to group by the Bread entry id, but get the different quantities?</p>

<p>The goal is to consider all entries with same id as "one", and to make it easy to sum them together.</p>

<matrix><entries-field><group>
Outputting Matrix blocks with grouped values based on Entries field id
# Outputting Matrix blocks with grouped values based on Entries field id

(Asked by: username_0 on 2015-09-07)

This is the setup:

I have a Matrix field called Breads. There is 1 block called Bread.

Within, I have two fields:

* An Entries field called Selected bread (limited to 1 entry)
* A Number field called Quantity.

Lets say I have 3 rows. Row 1 and 3 have the same entry selected, but different quantities. Is there a way to group by the Bread entry id, but get the different quantities?

The goal is to consider all entries with same id as "one", and to make it easy to sum them together.

**Tags:** matrix, entries-field, group


---

## 1 answers

### Answer by username_1 on 2015-09-07. Score: 4 | Accepted answer

Try something like:
{% set breadGroups = entry.breads | group('bread.first.id') %}

{% for breadId, blocks in breadGroups %}

    {% set sum = 0 %}

    {% for block in blocks %}

        {% set sum = sum + block.quantity %}

    {% endfor %}

    Total qty for Bread ID {{ breadId }}: {{ sum }}

 {% endfor %}

The group filter consumes a list — in this base, an array of Matrix blocks — and produces an array of arrays where the key is the grouping parameter, and the value is an array of items from the original list for which the group criteria matches the key.
c.f. Craft docs: http://buildwithcraft.com/docs/templating/filters#group


---

