在树枝中重组阵列
我想倒入数组,以便第一个类别是首先,以便以后可以更好地管理自己的foreach。 我设法实现了它,但是Merge删除了相同的密钥。而且我不应该将值添加为数组中的另一个项目。
默认数组:
array:10 [
0 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 1"
category: "Cat1"
}
]
1 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 2"
category: "Cat2"
}
]
2 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 3"
category: "Cat1"
}
]
3 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 4"
category: "Cat2"
}
]
合并后:(已删除了两个记录:()
array:2 [
"Cat1" => array:2 [
"type" => "type1"
"object" => ...
]
"Cat2" => array:2 [
"type" => "type1"
"object" => ...
]
]
他试图实现什么?
array:2 [
"Cat1" => array:2 [
0 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 1"
category: "Cat1"
}
]
1 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 3"
category: "Cat1"
}
]
]
"Cat2" => array:2 [
0 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 2"
category: "Cat2"
}
]
1 => array:2 [
"type" => "type1"
"object" => {
name: "Sample name 4"
category: "Cat2"
}
]
]
]
代码:
{% set organised_cats = {} %}
{% for element in sourceElements %}
{% set organised_cats = organised_cats|merge({
(element.object.category) : element
}) %}
{% endfor %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先是仅供参考,这不是您在模板中应该做的事情,因为代码非常混乱。无论如何,这是您在
twig
中合并/组数组的方式:demo
recsated问题
First a FYI though, this is not something you should be doing in the template, cause the code is pretty messy. Anyway here is how you merge/group arrays in
twig
:demo
related problem
issues with merge in twig