2017-08-10 58 views
0

我也很想知道它們都是什麼名字?例如一個數組項引用像$ item ['名稱']和$ item->名稱,如果有一個術語給他們! (不是關鍵,值)

$items = collection([ 
    [ 
     'name' => 'test item 1', 
     'description' => 'this is a description', 
    ], 
    [ 
     'name' => 'test item 1', 
     'description' => 'this is a description', 
    ], 
    [ 
     'name' => 'test item 1', 
     'description' => 'this is a description', 
    ], 
]); 

然後在刀片或任何ID愛能夠引用他們像

foreach($items as $item) { 
    echo $item->name; 
} 

,而不是

foreach($items as $item) { 
    echo $item['name']; 
} 

編輯

解決謝謝你們的答案。

$collection->map(function ($section) { 
    return (object) [ 
     'label' => $section['label'], 
     'items' => collect($section['items'])->map(function ($item) { 
      return (object) $item; 
     }), 
    ]; 
}); 

下面的完整代碼還用於檢查集合中是否存在項目。

protected $collection = []; 

public function __construct() 
{ 
    parent::__construct(); 
    $this->collection = collect([ 
     [ 
      'label' => 'Section label 1', 
      'items' => [ 
       [ 
        'label' => 'Item label 1', 
        'description' => 'Item description', 
       ], 
      ], 
     ], 
     [ 
      'label' => 'Section label 2', 
      'items' => [ 
       [ 
        'label' => 'Item label 2', 
        'description' => 'Item description', 
       ], 
      ], 
     ], 
     [ 
      'label' => 'Section label 3', 
      'items' => [ 
       [ 
        'label' => 'Item label 3', 
        'description' => 'Item description', 
       ], 
      ], 
     ], 
    ]) 
    ->map(function ($section) { 
     return (object) [ 
      'label' => $section['label'], 
      'items' => collect($section['items'])->map(function ($item) { 
       return (object) $item; 
      }), 
     ]; 
    }); 
} 

public function show($slug = '') 
{ 
    $item = $this->getItem($slug); 

    if (null === $item) { 
     abort(404); 
    } 

    return view('show') 
     ->withItem($item); 
} 

protected function getItem($slug) 
{ 
    return $this 
     ->collection 
     ->flatMap(function ($section) { 
      return $section->items; 
     }) 
     ->first(function ($item) use ($slug) { 
      return str_slug($item->label) === $slug; 
     }); 
} 
+1

所以你需要創建'object',而不是'array'。 – JYoThI

+1

瑞科利克打敗了我。要完成你的問題,在這裏命名'$ item-> name'是對象的一個​​屬性。此外,作爲一個函數收集不存在,它只需要'collect()' – mbozwood

+0

這是要麼收集(['數組項'去']或'新照明\支持\收藏(['數組項' ])'not'collection()' –

回答

1

可以使用Collection::mapobject

here功能。

$items = $items->map(function($item) { return (object) $item; }) 

然後在你的模板:

@foreach ($items as $item) 
    {{ $item->name }} 
@endforeach 
+0

感謝你們,它幫助我解決了我的對象問題,我將更新我的代碼。 –

2

試試這個

$items= json_decode(json_encode((object) $items), FALSE); 

json_decode第二個參數,如果屬實,將結果轉換爲array否則結果僅供參考

相關問題