2017-08-10 9 views
0

どちらの名前も知りたいですか?例えば$ item ['name']のように参照される配列項目、およびそれらの用語があれば$ item-> nameです! (キーではない、値)

$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']; 
} 

EDIT

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

ので、あなたの代わりにarray' 'のobject''作成する必要があります。 – JYoThI

+1

Regolithがそれに私を打ち負かした。あなたの質問を完成させるために、ここで '$ item-> name'という名前はオブジェクトのプロパティです。また、関数としてのコレクションが存在しないので、 'collect()'だけにする必要があります – mbozwood

+0

'collect '['配列アイテムはここに ']'または 'new Illuminate \ Support \ Collection([配列アイテム' ]) 'not' collection() ' –

答えて

1

を探しhereobject

であるあなたがCollection::mapを使用することができ、他のarrayに結果を変換します真の場合は、2番目のパラメータこの

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

json_decodeを試してみてください関数。

テンプレートで次に
$items = $items->map(function($item) { return (object) $item; }) 

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

ありがとう、これは私が私のコードに私が使用した更新を掲載する私のオブジェクトを解決するのを助けた。 –

関連する問題