2017-02-21 2 views
1

Laravel 5.3에서 수집을 사용해야하지만 도움이 필요합니다. 예를 들어수집품을 Laravel 5.3에서 사용하는 방법?

:

$collection = collect([ 
    'Apple' => [ 
     ['name' => 'iPhone 6S', 'price' => '200'], 
     ['name' => 'iPhone 7S', 'price' => '250'], 
    ], 
    'Samsung' => [ 
     ['name' => 'Galaxy S7', 'price' => '300'] 
     ['name' => 'Galaxy note', 'price' => '150'] 
    ], 
]); 
  1. 어떻게 수집과 Apple 또는 Samsung 이름을 얻는 방법? 나는 브랜드 이름을 얻을 필요가있다.
  2. 각 브랜드의 가장 저렴한 가격 (이름과 가격)을 얻는 방법.

당신은 최소 가격을 얻을 수있는 내부 하나의 외부 배열과 분을 통과하기 위해 각을 사용해야 할 것

+0

를 얻으려면합니까? –

+0

안녕하세요 @curious_coder, 네,하지만 제 질문에 답을 찾지 못했습니다! – mySun

+0

원하는 출력물을 보여줄 수 있습니까? –

답변

2

당신은 mapWithKeys

/* First get the minimum price */ 

$min = $collection->flatten(1)->pluck('price')->min(); 

/* Then perform the filteration */ 

$final = $collection->mapWithKeys(function($value, $key) use ($min) { 
    $result = collect($value)->filter(function($inner) use ($min){ 
     return $inner['price'] === $min; 
    })->keys()->first(); 

    return $result ? [$key => $value[$result]]: []; 
}); 

을 통해 그것을 달성 할 수있는 모든 컬렉션을 둥지 위 코드를 입력하시면

Illuminate\Support\Collection Object 
(
    [items:protected] => Array 
     (
      [Samsung] => Array 
       (
        [name] => Galaxy note 
        [price] => 150 
       ) 

     ) 

) 

간단히 브랜드 이름을 얻으실 수 있습니다.

$final->keys()->first() // Samsung 

당신이 문서를 참조나요 모델 이름

$final->pluck('name')->first() // Galaxy note 
1

:-) 주셔서 감사합니다. 그런 다음 색인을 찾고 다시 돌아가 이름/가격을 얻으려고 검색해야합니다. 그 속도로, 당신은 아마 더 잘 읽는 자신의 함수를 작성하는 것이 가장 좋습니다.

$collection->each(function ($item, $brand) { 
    $minPrice = $item->min('price'); 
    $minIndex = $item->search(function ($item) use ($minPrice) { 
     return $item['price'] == $minPrice 
    }); 
    echo $brand.' '.$item[$minIndex]['name']. ' '.$item[$minIndex]['price']; 
}); 

당신은 자동으로 수집 할 경우 내가 기억 할 수 없기 때문에 내부 항목을 수집 할 수 있습니다 당신이를 실행하면

관련 문제