比方說,我有這樣的集合:
$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']]
]]);
此集合在遞歸FUNC使用。在每一個循環我wan't像這樣進行的東西:
$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屬性。
你不能只使用'$ collection-> push()'? – PawelMysior
不完全,push()不會在每個輸入上創建新的索引。 – Skeletor
那麼,比'$ collection-> put($ key,$ value)'怎麼樣? – PawelMysior