【问题标题】:Foreach loop stores only first index of multidimensional array | LaravelForeach 循环仅存储多维数组的第一个索引 |拉拉维尔
【发布时间】:2020-12-29 02:19:18
【问题描述】:

我正在尝试将多维数组值保存到单独的字符串中并将它们存储在数据库中。我有以下数组: 我的回复数据:

[
  {
        "name": "bla bla",
        "creator": "bla bla",
        "cost": 200
    }, {
        "name": "bla bla",
        "creator": "bla bla",
        "cost": 200
    },
    {
        "name": "bla bla",
        "creator": "bla bla",
        "cost": 200
     }
  ]

我尝试过单个 foreach 循环(如下所示),此代码当前正在运行,但仅接受(保存)第一个索引。我有将近 10K 的数据。我需要它为每个数组值返回结果。

public function fileImport(Request $request) 
{   
    set_time_limit(6000);
    $array = (new DrugsImport)->toArray($request->file('file'));
    $i = 0;
    foreach ($array as $item) {
        $drugs = new Drug;
        $drugs->user_id = 1;
        $drugs->name = $item[$i]['name'];
        $drugs->cost = $item[$i]['cost'];
        $drugs->save();
        //$name = utf8_decode($item[$i]['naimenovaniya']);
        // $name = $item[$i]['naimenovaniya'];
        // iconv("Windows-1251", "UTF-8", $name);
        $i++;
    }
    return response()->json($drugs);

   //Excel::import(new DrugsImport, $request->file('file')->store('temp'));
   //return back();
}

目前,此代码仅存储第一个 [0] 元素。剩余的值不会被保存。我也尝试过使用其他一些方法,但在所有第一个元素中存储。 我也试过这样:

    foreach ($array as $key => $value) {
    if (is_array($value)) {
        ......
    }
}

我找不到我错的地方。任何人都可以帮忙吗? 谢谢!

已编辑 如果我使用var_dump($array) 运行:

    array(1) {
        [0] => array(2897) {
                [0] => array(3) {
                    ["name"] => string(36)
                    "bla bla bla" ["cost"] => int(200)
                } [1] => array(3) {
                     ["name"] => string(36)
                    "bla bla bla" ["cost"] => int(200)
                } [2] => array(3) {
                     ["name"] => string(36)
                    "bla bla bla" ["cost"] => int(200)
                } [3] => array(3) {
                     ["name"] => string(36)
                    "bla bla bla" ["cost"] => int(200)
                }
        ....

更新 我的 DrugsImport 文件:

    class DrugsImport implements ToModel, WithHeadingRow
{
    use Importable;

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Drug([
            'name '     => $row[0],
            'cost'    => $row[1]
        ]);
    }

}

如果我转储 $array 它会像这样返回:

array:1 [▼
0 => array:2897 [▼
0 => array:3 [ …3]
1 => array:3 [ …3]
2 => array:3 [ …3]
3 => array:3 [ …3]
4 => array:3 [ …3]
....

对不起,如果这是一个重复的问题,但他们都没有工作......

【问题讨论】:

  • 如果$array 是您首先发布的内容,那么$item[$i]['name'] 应该会针对未定义的索引发出警告。 $item 将是子数组,所以它应该只是 $item['name']。根本不需要$i
  • 你还有一个错字:['cose'] 应该是['cost']
  • 不,如果我使用$index['name'],它会返回错误Undefined index: name
  • 如果在循环之前转储数组,您会看到什么? dump($array)
  • 那么数组看起来不像你发布的那个。这是一个演示:3v4l.org/LlTXC

标签: php arrays laravel laravel-excel


【解决方案1】:

你可以这样试试。 如果您遇到错误,请告诉我们

// controller fileImport     
public function fileImport(Request $request) 
{   
   $drug = new DrugsImport;
   Excel::import($drug, $request->file('file'));
   return $drug->drugResult;
} 

// Drug Import 
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToCollection;
class DrugsImport implements ToCollection, WithHeadingRow
{
      public $drugResult;
      public function collection(Collection $rows)
      {
          $this->drugResult = $rows;
      }
} 

【讨论】:

  • 谢谢,这种方式可行,但我需要另一种方式。我需要对数组中的值(拆分、修剪等)执行必要的操作。这必须在控制器中导入。
  • 什么是必要的行动?我看不懂
  • 对不起,我的英文不是很好,我要删除数组中的一些值,我需要编辑这些值,所以在控制器中是必要的。
【解决方案2】:

因此,您的代码存在一些问题。

格式

你的数组是一个包含一个数组又包含多个数组的数组,所以如果你只这样做:

foreach ($array as $item)

它只会迭代一次(因为$array 只包含一个数组),这就是为什么你只得到第一个。

如果你这样做

foreach ($array[0] as $item)

并使用$item['name'],它将遍历所有项目。

为什么只返回最后一个?

那是因为您在每次迭代时都覆盖了 $drugs 变量。

如果您想将它们全部返回,请将它们添加到数组中。应该这样做:

// Define the array where we will add the drugs so we can return them all
$listOfDrugs = [];

foreach ($array[0] as $item) {
    $drug = new Drug;
    $drug->user_id = 1;
    $drug->name = $item['name'];
    $drug->cost = $item['cost'];
    $drug->save();       

    // Add the new drug to the array so it can be returned after the loop
    $listOfDrugs[] = $drug;
}

// Now return the array with all the drugs
return response()->json($listOfDrugs);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2016-02-06
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2015-06-02
    相关资源
    最近更新 更多