关于数组转collect的疑惑
1. 运行环境
1). 当前使用的 Laravel 版本?
Lavavel 9
2). 当前使用的 php/php-fpm 版本?
PHP 版本: PHP8.1
3). 当前系统
Ubuntu 20.4
2. 问题描述?
我使用collect()函数将一个数组转化为collect;代码如下
$test = collect(['name' => 'test' , 'id' => '123']);
dump($test);
dump($test->keys());
dump($test->get('name'));
dump($test->name);
dump($test->values());
然后想使用箭头访问属性,结果报错
^ Illuminate\Support\Collection^ {#840
#items: array:2 [
"name" => "test"
"id" => "123"
]
#escapeWhenCastingToString: false
}
^ Illuminate\Support\Collection^ {#841
#items: array:2 [
0 => "name"
1 => "id"
]
#escapeWhenCastingToString: false
}
^ "test"
Exception
Property [name] does not exist on this collection instance.
at vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php:983
979▕ */
980▕ public function __get($key)
981▕ {
982▕ if (! in_array($key, static::$proxies)) {
➜ 983▕ throw new Exception("Property [{$key}] does not exist on this collection instance.");
984▕ }
985▕
986▕ return new HigherOrderCollectionProxy($this, $key);
987▕ }
1 app/Console/Commands/Test.php:68
Illuminate\Support\Collection::__get()
+13 vendor frames
15 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
请问各位大佬:
如何将数组转化为collect后能通过->访问;
用foreach或者array_map添加吗。。。?
没办法。你可以自己创建一个集合类,继承内置的集合类,然后改写
__get
这个魔术方法,把他重定向到offsetGet
方法,创建集合的时候就需要使用自己的集合的 make 方法了,看起来像这样。