我想反轉我的陣列,以便首先將類別放在首位,以便以后可以更好地管理我的 foreach。 我設法實作了它,但合并洗掉了相同的鍵。而且我不應該將值添加為陣列中的另一個專案。
默認陣列:
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 %}
uj5u.com熱心網友回復:
首先僅供參考,這不是您應該在模板中執行的操作,因為代碼非常混亂。無論如何,這是您合并/分組陣列的方式twig:
{% set output = [] %}
{% for item in items %}
{% if not attribute(output, item.object.category) is defined %}
{% set output = output|merge({ (item.object.category) : {}, }) %}
{% endif %}
{% set output = output|merge({(item.object.category) : output[item.object.category] | merge([ item, ]) }) %}
{% endfor %}
{% for category, items in output %}
{{ category }}:
{% for item in items %}
{{ item.object.name }}
{% endfor %}
{% endfor %}
演示
相關問題
在樹枝中合并的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481783.html
下一篇:當我添加背景顏色時,按鈕停止作業
