나는 이제 이것에 대한 자체 해결책을 생각해 냈습니다.
1. 배열에서 특정 속성을 추출하는 일반 함수 생성
아래 함수는 연관 배열 또는 연관 배열의 배열에서 특정 속성 만 추출합니다 (마지막은 Laravel에서 $ collection-> toArray ()를 수행 할 때 얻는 것입니다).
다음과 같이 사용할 수 있습니다.
$data = array_extract( $collection->toArray(), ['id','url'] );
다음 기능을 사용하고 있습니다.
function array_is_assoc( $array )
{
return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}
function array_extract( $array, $attributes )
{
$data = [];
if ( array_is_assoc( $array ) )
{
foreach ( $attributes as $attribute )
{
$data[ $attribute ] = $array[ $attribute ];
}
}
else
{
foreach ( $array as $key => $values )
{
$data[ $key ] = [];
foreach ( $attributes as $attribute )
{
$data[ $key ][ $attribute ] = $values[ $attribute ];
}
}
}
return $data;
}
이 솔루션은 대규모 데이터 세트의 컬렉션을 반복 할 때 성능에 미치는 영향에 초점을 맞추지 않습니다.
2. 사용자 지정 컬렉션을 통해 위의 구현 i Laravel
$collection->extract('id','url');모든 컬렉션 개체에 대해 간단히 수행 할 수 있기를 원 하기 때문에 사용자 지정 컬렉션 클래스를 구현했습니다.
먼저 Eloquent 모델을 확장하지만 다른 컬렉션 클래스를 사용하는 일반 모델을 만들었습니다. 모든 모델은 Eloquent 모델이 아니라이 커스텀 모델을 확장해야합니다.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
public function newCollection(array $models = [])
{
return new Collection( $models );
}
}
?>
둘째로 다음과 같은 사용자 지정 컬렉션 클래스를 만들었습니다.
<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
public function extract()
{
$attributes = func_get_args();
return array_extract( $this->toArray(), $attributes );
}
}
?>
마지막으로, 모든 모델은 다음과 같이 대신 사용자 지정 모델을 확장해야합니다.
<?php
namespace App\Models;
class Article extends Model
{
...
이제 기능이 없습니다. 위의 1은 컬렉션에서 $collection->extract()메서드를 사용할 수 있도록 깔끔하게 사용됩니다 .
Collection::implode(). 속성을 가져와 컬렉션의 모든 개체에서 추출 할 수 있습니다. 이것은이 질문에 정확히 대답하지 않지만, 저처럼 Google에서 온 다른 사람들에게 유용 할 수 있습니다. laravel.com/docs/5.7/collections#method-implode