2016-09-29 200 views
0

我有一個數組就像這樣:循環通過陣列

enter image description here

我的問題是我如何可以通過對象的foreach。我想把每個關聯到一個容器。

所以,我想這一點:

foreach ($data['plates'] as $index => $element) { 
    //Don't worry about the container_id. 
    $plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save(); 
} 

,但似乎無法得到這個工作。任何想法我做錯了或失蹤?模型之間

板,型號

FYI-的關係

public function plateContainer() 
{ 
    return $this->belongsTo('App\Models\PlateContainer'); 
} 

PlateContainer型號

public function plates() 
{ 
    return $this->hasMany('App\Models\Plate'); 
} 

更新#1:該陣列由AngularJS後到來提交一個模擬形式。對不起忘了提到這一點。

更新#2:好的。我做了以下嘗試。

foreach ($data['plates'] as $element) 
{ 
    foreach ($element as $value) 
    { 
     $plates = Plate::find($value)->plateContainer()->associate($data['container_id'])->save(); 
    } 
} 

...但仍然沒有得到它的工作。檢查數據庫,它只顯示第一塊板已更新給定的容器。

我試圖dd($value);它僅示出了1

+0

它是一個JS數組或一個PHP數組? – Pete

+0

爲什麼在這裏標記javascript? – callback

+0

@callback對不起。我忘了提及。來自AngularJS的數組。我會更新帖子 – user3641381

回答

1

$data['plates']包含2個關聯數組:[0] => {等...}和[1] => {等...}。 所以你需要一個嵌套循環。

for ($i=0; $i<count($data['plates']); $i++) { 
    foreach ($data['plates'][$i] as $index => $element) { 
    //Don't worry about the container_id. 
    $plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save(); 
    } 
} 
+0

謝謝,但如果我有兩個以上的元素呢? – user3641381

+0

更新了我的答案。而不是硬編碼循環限制,而是使用count()函數來計算數組元素的數量。 –

+0

我又試了一次。這很奇怪,它只更新給定容器的單個板。我再次更新了我的帖子。 – user3641381

0

東西已關閉。

foreach ($data['plates'] as $index => $element) { 


    $plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save(); 
} 

的伎倆