将值推送到关联数组中的键

时间:2016-01-14 06:38:43

标签: php arrays

假设:

$groups           = EveMarketGroupsEntity::distinct()->select('name')->get();
$groupInformation = [];

if (!is_null($groups)) {
    foreach ($groups as $group) {
    }
}

如何正确执行以下

if (!is_null($groups)) {
    foreach ($groups as $group) {
        $groupInformation[$group->name][]= EveMarketGroupsEntity::where('name', $group->name)->first()->item();
    }
}

现在我得到:

array:818 [▼
  "Weaponry" => array:1 [▶]
  ...
]

Weaponry应该有多于1个元素时。事实上:

array:818 [▼
  "Weaponry" => array:1 [▶]
  "Special Edition Industrial Ships" => array:1 [▶]
  "Nanite Injectors" => array:1 [▶]
  "Vehicles and Gear" => array:1 [▶]
  "Rapid Light Missile Launchers" => array:1 [▶]
  "Standard Light Missiles" => array:1 [▶]
  "Jump Bridge" => array:1 [▶]
  "Missile Launcher Rigs" => array:1 [▶]
  "Strip Miners" => array:1 [▶]
  "Freighters" => array:1 [▶]
  ...
]

他们应该都有超过1个元素。 我缺少什么?

问题:如何将相同的元素推送到同一个键,从而创建一个数组:array('key' => [elm, elm, elm ...])

1 个答案:

答案 0 :(得分:0)

所以,(反馈是受欢迎的,特别是如果你对此投票的话)

foreach ($groups as $group) {
    $groupInformation[$group->name] = EveMarketGroupsEntity::where('name', $group->name)->first()->item()->get()->all();
}

这对我有用......

Larvel Collection - all() docs