laravel集合

时间:2016-09-07 05:03:15

标签: laravel collections

假设我有这个系列:

$collection = collect(['cars'=>[
[['id'=>'1'], ['brand'=>'ford'],['color'=>'green']],
[['id'=>'2'], ['brand'=>'audi'],['color'=>'yellow']],
[['id'=>'3'], ['brand'=>'bmw'],['color'=>'grey']],
[['id'=>'4'], ['brand'=>'honda'],['color'=>'black']]
]]);

此集合用于递归函数。在每个周期中,我都不想做这样的事情:

$collection->vehicles[] = $brand;

结果可能是:

'cars'=>[
[['id'=>'1'], ['brand'=>'ford'],['color'=>'green']],
[['id'=>'2'], ['brand'=>'audi'],['color'=>'yellow']],
[['id'=>'3'], ['brand'=>'bmw'],['color'=>'grey']],
[['id'=>'4'], ['brand'=>'honda'],['color'=>'black']],
'vehicles'=>['0'=>'ford', '1'=>'audi', '2'=>'bmw', '3'=>'honda']]

这实际上就是一个例子。我在这里寻找的是相当于$arr[] = $var。因此,每次添加值时,它都会自动添加并对其进行索引。还有其他的东西,如追加,推和放,但我找不到相当于此。是否有等价物或替代物?

-----------编辑提供更多细节---------------

我会保持简单,但我想我需要提供更多细节。我有一个递归函数,可以创建一个分层的类别集合。在创建此集合时,我想创建一个额外的属性来保存(单维平面)数组中的所有项目。所以我以后可以使用它(比如$ collection-> flat)并且不需要循环整个集合来展平它。

public static function toHierarchic($items, $parent_id=0, $newItems=null){
    if($newItems===null){ // create a collection for the begining
        $newItems = collect( $items->whereLoose('parent_id', $parent_id) );
    }
    foreach ($newItems as $itemKey => $newItem) {
        $newItem->flat[] = [$newItem-id=>$newItem->title];

        $newItem->children = $children;
        self::toHierarchicObject($items, $newItem->id, $newItem->children);
    }
    return $newItems;
}

$newItem->flat[] = [$newItem-id=>$newItem->title];之外,一切正常。这是我提出问题的部分。在每个cyle或递归中,我想将当前名称/ id添加到$ collection-> flat属性中。

1 个答案:

答案 0 :(得分:1)

如果这是您的汽车收藏品:

$collection = collect([
    ['brand' => 'ford', 'color' => 'green'],
    ['brand' => 'audi', 'color' => 'yellow'],
    ['brand' => 'bmw', 'color' => 'grey'],
    ['brand' => 'honda', 'color' => 'black']
]);

您可以按以下方式列出品牌:

$brands = $collection->pluck('brand');

假设您要添加汽车:

$collection->push(['brand' => 'audi', 'color' => 'black']);

如果您的系列中有多辆同品牌汽车,并且只想显示没有重复品牌的品牌列表,请按以下步骤操作:

$uniqueBrands = $collection->unique('brand')->pluck('brand');