【问题标题】:Lumen/Laravel - Method to extract specific property from objects in an array of objects?Lumen/Laravel - 从对象数组中的对象中提取特定属性的方法?
【发布时间】:2020-05-17 00:33:17
【问题描述】:

我有以下数据:

    [{
      "id": 1,
      "name": "test1",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 2,
      "name": "test12",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 3,
      "name": "test123",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 4,
      "name": "test1234",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 5,
      "name": "test12345",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 6,
      "name": "test123456",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 7,
      "name": "test1234567",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 8,
      "name": "test12345678",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 9,
      "name": "test123456789",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 10,
      "name": "test1234567890",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 11,
      "name": "test12345678901",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }, {
      "id": 12,
      "name": "test123456789012",
      "created_at": "2020-01-30 15:55:44",
      "updated_at": "2020-01-30 15:55:44"
    }]

此数据是通过 eloquent 模型检索到的,如下所示:

$ad_groups = Ad_user::find($request->decodedToken->user_id)->ad_groups()->get();

我不知道 eloquent 模型的任何“继承”功能是否仍然存在于 $ad_groups 中,这就是为什么我在这里为您发布它,以便您知道我们必须使用什么 ^^

我基本上想要完成的是提取 ids。我当然可以只写一个 foreach 循环。但是我是 Lumen/Laravel 的新手,我想知道在这种情况下是否还有一些很棒的方法,比如 ...>getMeWhatIWant() :D

【问题讨论】:

  • array_column 可以轻松做到这一点。
  • @04FS 出于某种原因,这不是一个数组,而是一个对象。我在它上面运行 is_array 和 is_object 并用 if/else 检查。当我使用 array_column 时,我得到这个错误:array_column() 期望参数 1 是数组,给定对象 为什么是这样,我该怎么办?
  • 这是因为 eloquent 返回的对象是模型的集合,因此不能将其用作数组。但是,这允许您对数据使用一些有用的方法(您可以在 documentation 中查看所有可用的方法),这些方法已经在 Laravel 核心中实现

标签: php laravel eloquent lumen


【解决方案1】:

您可以在 Laravel 集合 (official docs here) 上使用 pluck 方法。

您只需将要检索的列名作为第一个参数传递:

$ids = $ad_groups->pluck('id');
dd($ids);

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2010-11-10
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多