关于数组转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*/
    980public function __get($key)
    981{
    982if (! in_array($key, static::$proxies)) {983throw new Exception("Property [{$key}] does not exist on this collection instance.");
    984}
    985986return 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添加吗。。。?

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

没办法。你可以自己创建一个集合类,继承内置的集合类,然后改写 __get 这个魔术方法,把他重定向到 offsetGet 方法,创建集合的时候就需要使用自己的集合的 make 方法了,看起来像这样。

class UserCollection extends \Illuminate\Support\Collection
{
    public function __get($key)
    {
        if (array_key_exists($key, $this->items)) {
            return $this->items[$key];
        }
        return parent::__get($key);
    }
}
$val = UserCollection::make(['name' => 'test' , 'id' => '123']);
dd($val['name'], $val->name);
1年前 评论
____Laravel (楼主) 1年前
讨论数量: 9

没办法。你可以自己创建一个集合类,继承内置的集合类,然后改写 __get 这个魔术方法,把他重定向到 offsetGet 方法,创建集合的时候就需要使用自己的集合的 make 方法了,看起来像这样。

class UserCollection extends \Illuminate\Support\Collection
{
    public function __get($key)
    {
        if (array_key_exists($key, $this->items)) {
            return $this->items[$key];
        }
        return parent::__get($key);
    }
}
$val = UserCollection::make(['name' => 'test' , 'id' => '123']);
dd($val['name'], $val->name);
1年前 评论
____Laravel (楼主) 1年前

Collection 的目的就是为了批量处理一类数据,而不是这种没有共性的单一对象数据。

如果要通过箭头的方式访问,为什么不直接将数组转为 stdClass object 呢?

$obj = (object) ['name' => 'test', 'id' => '123'];
$obj->id;
1年前 评论
____Laravel (楼主) 1年前
GeorgeKing (作者) 1年前
____Laravel (楼主) 1年前
游离不2

collection 没有 -> 访问属性功能吧,你可能需要的是 DTO

1年前 评论
____Laravel (楼主) 1年前

结贴:感谢各位热心回复,
1楼大佬从实际解决了问题,更加切题,选为答案

2楼大佬解决了思路问题,帮助更大,建议有我同样疑惑的phper参考。

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!