duan0818 2016-09-29 14:32
浏览 57

循环遍历数组

I have an array just like this:

enter image description here

The question I have is how can I foreach through the objects. I want to associate each of those to a container.

So I tried this:

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

But can't seem to get this working. Any ideas what I am doing wrong or missing?

FYI—The relations between the models

Plate Model

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

PlateContainer Model

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

Update #1: The array is coming from AngularJS after submitting a simple form. Sorry forgot to mention this.

Update #2: Ok. I gave the following a try.

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

…but still not getting it to work. Checking the DB, it only shows the first plate was updated with the given container.

I tried dd($value); It only shows 1

  • 写回答

2条回答 默认 最新

  • duanbi3151 2016-09-29 14:45
    关注

    Your $data['plates'] contains 2 associative arrays: [0] => {etc...} and [1] => {etc...}. So you need a nested loop for that.

    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();
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助