简体   繁体   中英

How to break long array into subarrays returned from functions in PHP?

I have this PHP function in Laravel (in my database seeder):

DB::table('table_name')->insert([
   [first_record],
   [second_record],
   ...
   [nth_record]
]);

I can't use faker libraries and I need to specify each record. However, I decided to break this method into smaller methods this way:

public function run() 
{
    DB::table('table_name')->insert([
       $this->firstMethodToReturnPartOfArray(),
       $this->secondMethodToReturnPartOfArray(),
       ...
       $this->nthMethodToReturnPartOfArray()
    ]);
}

public function firstMethodToReturnPartOfArray()
{
    return [
        [first_record],
        [second_record],
        ...
        [nth_record]
    ];
}

public function secondMethodToReturnPartOfArray()
{
    return [
        [first_record],
        [second_record],
        ...
        [nth_record]
    ];
}

But I get this error:

Array to string conversion
at vendor/laravel/framework/src/Illuminate/Support/Str.php:524

I'm new to PHP and Laravel. How should I fix this?

The error is that for insert , where you have [first_record], - you are passing in an array of records (the return values of firstMethodToReturnPartOfArray etc is an array of records).

You could merge the results of the two (or more) methods and then use ... to put the results back into the call

DB::table('table_name')->insert([
   ...array_merge($this->firstMethodToReturnPartOfArray(),
         $this->secondMethodToReturnPartOfArray(),
         $this->nthMethodToReturnPartOfArray());
]);

(Note that the ... is intentional and not some form of abbreviation).

Or as I mentioned, load it from a file.

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