2016-11-13 74 views
0

我想一個數組轉換爲一個集合,映射了它。但是我收到一個錯誤:Laravel收集工作不

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" => [] 
] 

回答

1

你應該使用箭頭,其目的在於這樣的訪問ID:

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

希望這有助於!

+0

這是我收到的問題:'''試圖讓非object''' – Jamie

+0

財產嘗試打印$選項裏面什麼? –

+0

請參閱我的編輯。 – Jamie

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); 
    } 
}); 

希望得到這個幫助!

+0

嗨,謝謝幫助。它看起來像'''$ option ['id'];'''不是空的。但是它不能在'''$ this-> options-> contains('id',$ option ['id'])中被訪問''' – Jamie

0

我覺得$this上下文是遙不可及的這種情況。您可以嘗試設置它傳遞明確地,像這樣:

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