我现在提出了自己的解决方案:
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.通过Laravel的自定义集合实现以上内容
由于我希望能够简单地对任何集合对象执行$collection->extract('id','url');,因此我实现了一个自定义集合类。
首先,我创建了一个通用模型,该模型扩展了Eloquent模型,但是使用了一个不同的集合类。 您所有的模型都需要扩展此自定义模型,而不是Eloquent模型。
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 );
}
}
?>
其次,我创建了以下自定义集合类:
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 );
}
}
?>
最后,所有模型都应改为扩展自定义模型,例如:
namespace App\Models;
class Article extends Model
{
...
现在的功能从无到有。 集合巧妙地使用上述1来使$collection->extract()方法可用。