使用 Twig 使两个数组相交

2024-01-04

我有两个想要相交的数组。 我得到了这两个数组:

{{ 转储(数组1) }}

array(6) {
  [0]=>
  array(2) {
    ["id"]=>
    int(121)
    ["text"]=>
    string(3) "uno"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(122)
    ["text"]=>
    string(3) "dos"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(123)
    ["text"]=>
    string(4) "tres"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [4]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [5]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
}

{{ 转储(数组2) }}

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(127)
    ["text"]=>
    string(5) "siete"
  }
}

我希望我的第三个数组有这样的结果:

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
}

问题是:如何使用树枝中的简单过滤器将它们相交?


for anyone ending up here and having a sane use case and looking for an actual solution... ;)

树枝array filter filter https://twig.symfony.com/doc/2.x/filters/filter.html结合x in array_y应该可以让你到达那里(在 Twig 1.41 和 2.10 中添加):

{% set arr_a = ['lemon', 'apple', 'peach', 'banana', 'orange', 'pear'] %}
{% set arr_b = ['mango', 'peach', 'orange', 'lemon', 'melon'] %}

{{ arr_a | filter((fruit) => fruit in arr_b) | join(', ') }}

柠檬、桃子、橙子

树枝小提琴在这里 https://twigfiddle.com/pniyp8

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Twig 使两个数组相交 的相关文章

随机推荐