Laravel Collection无法正常工作

时间:2016-11-13 16:52:11

标签: php laravel collections

我正在尝试将数组转换为集合并映射到它。但我收到一个错误:

ErrorException in Poll.php line 90:
Undefined index: id

代码:

$options = collect($options);
$options->map(function($option) {
   if($this->options->contains('id', $option['id'])) { //line 90
        Option::create($option);
   }
});

当我dd($options);时,它看起来像这样:

Collection {#390
  #items: array:4 [
    0 => array:7 [
      "id" => 17
      "slug" => "asdf-1"
      "name" => "asdf"
      "poll_id" => 6
      "created_at" => "2016-11-13 17:39:01"
      "updated_at" => "2016-11-13 17:39:01"
      "votes" => []
    ]
    1 => array:7 [
      "id" => 18
      "slug" => "asdfkowugiw"
      "name" => "asdfkowugiw"
      "poll_id" => 6
      "created_at" => "2016-11-13 17:39:01"
      "updated_at" => "2016-11-13 17:39:01"
      "votes" => []
    ]
    2 => array:7 [
      "id" => 21
      "slug" => "asdf-1"
      "name" => "asdf"
      "poll_id" => 6
      "created_at" => "2016-11-13 17:48:37"
      "updated_at" => "2016-11-13 17:48:37"
      "votes" => []
    ]
    3 => array:7 [
      "id" => 22
      "slug" => "asdfkowugiw"
      "name" => "asdfkowugiw"
      "poll_id" => 6
      "created_at" => "2016-11-13 17:48:37"
      "updated_at" => "2016-11-13 17:48:37"
      "votes" => []
    ]
  ]
}

所以这是一个集合所以我应该能够做到这一点吗?:

$options = collect($options);
$options->map(function($option) {
   if($this->options->contains('id', $option->id)) {
        Option::create($option);
   }
});

但那失败了。这有什么不对?

- 编辑 -

array:7 [
  "id" => 17
  "slug" => "asdf-1"
  "name" => "asdf"
  "poll_id" => 6
  "created_at" => "2016-11-13 17:39:01"
  "updated_at" => "2016-11-13 17:39:01"
  "votes" => []
]

3 个答案:

答案 0 :(得分:1)

您应该使用箭头作为对象来访问id,如下所示:

$options = collect($options);
$options->map(function($option) {
   if($this->options->contains('id', $option->id)) { //line 90
        Option::create($option);
   }
});

希望这有帮助!

答案 1 :(得分:1)

正如@Saumya Rastogi指出的,我也怀疑问题来自$options数据。某些项目可能没有id密钥。所以希望通过isset()进行简单的检查可以解决问题(或者如果你想要Laravel方式,你可以使用array_has())。

$options = collect($options);

$options->map(function ($option) {
    // Make sure that "id" key is exsits.
    if (isset($option['id']) && $this->options->contains('id', $option['id'])) {
        Option::create($option);
    }
});

希望这有帮助!

答案 2 :(得分:0)

我认为$this背景在这种情况下是遥不可及的。您可以尝试设置明确传递它,如下所示:

$options = collect($options);
$opts = $this->options;
$options->map(function($option) use ($opts) {
  if($opts->contains('id', $option->id)) {
    Option::create($option);
  }
});