简体   繁体   中英

Foreach loop stores only first index of multidimensional array | Laravel

I'm trying to save multidimensional array values into separate strings and store them in the database. I have the following array: My response data:

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

I have tried single foreach loops (like below), this code is currently working but only accepts (save) only the first index. I have almost 10K of data. I need it to return results for each array values.

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

Currently, this code stores only the first [0] element. The remaining values are not saved. I've also tried using a few other ways but in all of the first element stored. I tried also like this:

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

I can't find where I'm wrong. Can anyone help? Thank you!

EDITED If i run using 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)
                }
        ....

UPDATED My DrugsImport file:

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

}

if I dump $array it returns like that:

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]
....

Sorry if it's a duplicate question, but none of them worked ...

you can try like this. let we know if you get an error

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

So, there are a few issues with your code.

The format

Your array is an array that contains one array that contains multiple arrays, so if you only do:

foreach ($array as $item)

it will only iterate it once (since $array only contains one array), which is why you only got the first.

If you do

foreach ($array[0] as $item)

and use $item['name'] , it will iterate through all items.

Why does it only return the last?

That's because you're overwriting the $drugs variable on each iteration.

If you want to return them all, add them to an array instead. This should do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM