merge
¶
The merge
filter merges an array with another array:
マージ フィルタは、配列を別の配列とマージします。
1 2 3 4 5 |
{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}
{# values now contains [1, 2, 'apple', 'orange'] #}
|
New values are added at the end of the existing ones.
新しい値は、既存の値の最後に追加されます。
The merge
filter also works on hashes:
マージ フィルターはハッシュでも機能します。
1 2 3 4 5 |
{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}
{# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' } #}
|
For hashes, the merging process occurs on the keys: if the key does not already exist, it is added but if the key already exists, its value is overridden.
ハッシュの場合、マージ プロセスはキーに対して行われます。キーがまだ存在しない場合は追加されますが、キーが既に存在する場合はその値が上書きされます。
Tip
ヒント
If you want to ensure that some values are defined in an array (by given default values), reverse the two elements in the call:
一部の値が (指定されたデフォルト値によって) 配列で定義されていることを確認したい場合は、呼び出しで 2 つの要素を逆にします。
1 2 3 4 5 |
{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
{% set items = { 'apple': 'unknown' }|merge(items) %}
{# items now contains { 'apple': 'fruit', 'orange': 'fruit' } #}
|
Note
ノート
Internally, Twig uses the PHP array_merge function. It supports Traversable objects by transforming those to arrays.
内部的に、Twig は PHP の array_merge 関数を使用します。それらを配列に変換することにより、Traversable オブジェクトをサポートします。