修改数组多维symfony

时间:2017-10-23 22:22:44

标签: arrays symfony

使用数组/多维数组时,我感到非常困惑。我知道基本的东西,但我无法开始工作以下示例:

"hello":{
  "id":100,
  "items":[
     {
        "a":3,
        "b":1,
        "c":2
     }
  ]
}

我的代码:

public function createHello()
{
    $collection = $this->greetings->getItems();

    $hello = [
        'id'=> $this->getId(),
        'items' => [
        ]
    ];

    foreach ($collection as $col) {
        $hello['items'][]['a'] = $this->getValue($col);
    }

    return $hello;
}

这就是显示的内容:

hello:{
 "id": 100,
 "items": [
    [],
    {
       "a": 3
    }
  ]
}

如何解决这个问题?我继续切换数组的值和定义,但没有任何帮助。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我发现自己是解决方案:

public function createHello()
{
    $collection = $this->greetings->getItems();
    $hello = [ 
       'id'=> $this->getId(),
    ];

    foreach ($collection as $col) {
        $hello['items'][] = $this->getItems($col);
    }

    return $hello;
}


public function getItems($col)
{
    $a = ..;
    $b = ..;
    $c = ..;
    $items = [
        'a' => $a,
        'b' => $b,
        'c' => $c
    ]

    return $items;
}
相关问题