本文概述
对于PHP开发人员而言, 将项目追加到现有数组很容易, 就像使用array_push一样。遗憾的是, 如果不创建自定义扩展名, 则无法在Twig上使用相同名称的方法或过滤器, 但是使用合并过滤器可以达到良好的效果。
非关联数组
如果原始数组不具有关联性, 并且你想附加一个项目, 而忽略值的类型, 则合并过滤器期望将其内容将与分配的变量合并的数组作为第一个参数:
{% set myArray = [] %}
{% set myArray = myArray|merge([1]) %}
{% set myArray = myArray|merge([2, 3]) %}
{% set myArray = myArray|merge([4]) %}
{#
The content of myArray is
myArray = [1, 2, 3, 4]
#}
请注意, 你可以使用相同的语法构建任何复杂的内容:
{% set myArray = [] %}
{% set myArray = myArray|merge([
[1, 2], [3, 4], [5, 6]
]) %}
{% set myArray = myArray|merge([
[
[1, 2]
], [
[3, 4]
], ]) %}
{#
The content of myArray is
myArray = [
[
1, 2
], [
3, 4
], [
5, 6
], [
[1, 2]
], [
[3, 4]
]
]
#}
关联数组
要将项目添加到关联数组, 你只能将带有新值的带有方括号的数组作为第一个参数传递:
{# Note that the original array in this case has an item #}
{% set myArray = {
"first": 1
} %}
{% set myArray = myArray|merge({
"second": 2
}) %}
{% set myArray = myArray|merge({
"third": 3
}) %}
{#
The content of myArray is
myArray = {
"first":1, "second":2, "third":3
}
#}
请注意, 合并过滤器在后台使用array_merge, 这意味着如果你正在使用关联数组, 则如果键已经存在于元素上, 它将被覆盖:
{# Note that the original array in this case has an item #}
{% set myArray = {
"first": 1
} %}
{# Add the "second" key with value 2 #}
{% set myArray = myArray|merge({
"second": 2
}) %}
{# Change the value of the "second" key#}
{% set myArray = myArray|merge({
"second": "Modified 2"
}) %}
{#
The content of myArray is
myArray = {
"first":1, "second":"Modified 2"
}
#}
编码愉快!
评论前必须登录!
注册