树枝中的动态多维数组

测试 Testauskas

我有一个数组,但我需要重组它。我只能在树枝上做到这一点。

原始数组元素如下所示$arr[0]

"_id" => array:3 [
"cityName" => "someCityName"
"id" => 111
"className" => "someClassName"
  ]
"count" => 85

我的结果数组元素应该看起来像 $arr[0]:

"someCityName" => [
    12 => [
        "someClassName" => 32,
        "someOtherClassName" => 44
    ]
]

在 php 中我会做

$arr[$cityName][$id][$className] = $count;

这会起作用,但这必须在树枝中完成。

我希望使用树枝合并,但是当我尝试做

{% for infoArr in result %}
{% set cityName = infoArr['_id']['cityName'] %}
{% set id = infoArr['_id']['id'] %}
{% set class = infoArr['_id']['className'] %}
{% set countCity.cityName = countCity.cityName|merge({(id):([])}) %}    

{% 结束为 %}

要么

{% set countCity[cityName] = countCity[cityName]|merge({(id):([])}) %}

错误是值“[”的意外标记“标点符号”(预期“语句块结束”)

.

这应该如何正确地在树枝上完成?

黑蜂

如果你想在 中做这样的事情twig,我鼓励这样做,你需要重建数组的每个部分。另请注意,您不能merge与数字 indeces 一起使用,否则数据将被附加,而不是被覆盖。关于这个问题的更多信息在这里

$data = [
    'data' => [
        [
            '_id' => [
                'cityName'  => 'foo',
                'className' => 'alpha',
                'id'        => 42,
            ],
            'count' => 40,
        ],
        [
            '_id' => [
                'cityName'  => 'bar',
                'className' => 'alpha',
                'id'        => 55,
            ],
            'count' => 123,
        ],
        [
            '_id' => [
                'cityName'  => 'foo',
                'className' => 'beta',
                'id'        => 42,
            ],
            'count' => 99,
        ],
    ],
];

{% set output = {} %}

{% for raw in data %}
    {% if not attribute(output, raw._id.cityName) is defined %}
        {% set output = output|merge({ (raw._id.cityName) : {}, }) %}
    {% endif %}

    {% if not attribute(output[raw._id.cityName], 'id_'~raw._id.id) is defined %}
        {% set output = output|merge({(raw._id.cityName) : output[raw._id.cityName] | merge({('id_'~raw._id.id):[], }) }) %}
    {% endif %}

    {% set output = output|merge({(raw._id.cityName) : output[raw._id.cityName] | merge({('id_'~raw._id.id): output[raw._id.cityName]['id_'~raw._id.id]|merge({(raw._id.className): raw.count}), }) }) %}
{% endfor %}


{{ output.foo.id_42.alpha }} {# output: 40 #}

演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章