繁体   English   中英

在 Laravel 中将集合转换为 I=ID 的数组

[英]Convert Collection to Array with I=ID in Laravel

我是初学者 php 开发人员。 我的阵列有小问题。 我在我的项目 Laravel 7 中使用了以下代码:

$items = collect($discount->products->toArray());

结果我:

Illuminate\Support\Collection {#1783 ▼
  #items: array:2 [▼
    0 => array:17 [▼
      "id" => 1
      "product_category_id" => 5
      "image_id" => null
      "vat_type_id" => 1
      "name" => "Produkt 1"
      "slug" => "produkt-1"
      "lead" => "<p>fewferfer</p>"
      "description" => "<p>&nbsp;</p>"
      "price" => "123.00"
      "loyalty_program_points_price" => 2
      "min_student_level" => null
      "marked_as_available_at" => "2020-09-30T11:45:51.000000Z"
      "deactivated_at" => null
      "created_at" => "2020-09-30T11:45:23.000000Z"
      "updated_at" => "2020-09-30T11:45:51.000000Z"
      "deleted_at" => null
      "pivot" => array:3 [▶]
    ]
    1 => array:17 [▼
      "id" => 2
      "product_category_id" => 5
      "image_id" => null
      "vat_type_id" => 1
      "name" => "Produkt 2"
      "slug" => "produkt-2"
      "lead" => "<p>&nbsp;</p>"
      "description" => "<p>fergfer</p>"
      "price" => "21.00"
      "loyalty_program_points_price" => 3
      "min_student_level" => null
      "marked_as_available_at" => "2020-09-30T11:45:38.000000Z"
      "deactivated_at" => null
      "created_at" => "2020-09-30T11:45:38.000000Z"
      "updated_at" => "2020-09-30T11:45:38.000000Z"
      "deleted_at" => null
      "pivot" => array:3 [▶]
    ]
  ]
}

我需要将它转换为这个结果:

Array{
    1 => 1 (id)
    2 => (id)
}

我怎样才能做到? 我需要只有 id 值的数组

集合具有pluck 方法,它允许您获取特定键的所有值。 要获得所有的 id,你只需要做

$ids = $items->pluck('id')->all();

如果您希望它们也具有与 id 相同的键,请将其作为第二个参数传递

$ids = $items->pluck('id', 'id')->all();

请注意,如果 products 是一个关系,那么它已经是一个集合。 您不需要将其转换为数组,然后再转换回集合:

$product_ids = $discount->products->pluck('id')->all();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM