首页 > 解决方案 > 在 foreach 中运行时返回无意义的数组数组

问题描述

我的项目有一个由请求组成的数组,里面有一个输入数组,如下所示:

array:8 [▼
  "type_id" => array:1 [▼
    0 => "1"
  ]
  "zip_code" => array:1 [▼
    0 => "88801500"
  ]
  "street_address" => array:1 [▼
    0 => "Avenida Getúlio Vargas"
  ]
  "number" => array:1 [▼
    0 => "asdasd"
  ]
  "street_address_2" => array:1 [▼
    0 => "asdasd"
  ]
  "city_id" => array:1 [▼
    0 => "4384"
  ]
  "neighborhood" => array:1 [▼
    0 => "Centro"
  ]
  "created_by" => 2
]

但是,当我尝试在 foreach 上运行所述数组以将其插入数据库时​​,我得到一个没有意义的结果:

array:1 [▼
  0 => "1"
]

我的代码:

dd($dataEnderecos); //This is for debug purposes, it shows the initial array on this question.
        foreach ($dataEnderecos as $enderecos) {
            dd($enderecos); //This is for debug purposes, it shows the secondary array on this question.
            $enderecoID = $this->address->create($enderecos)->id;
            $this->repository->enderecos()->attach($enderecoID);
        }

标签: phparrayslaravel

解决方案


我设法通过使用 for 循环并使用另一个变量来接收初始数组的结果来解决这个问题:

for ($i = 0; $i < $limit; $i++) {
   $insert = array(
      'type_id'          =>   $dataEnderecos['type_id'][$i],
      //                         ^^^^           ^^^^   ^^^^
      //                Initial Array  Secondary Array Index
   );
}

推荐阅读