【发布时间】:2021-04-05 15:42:06
【问题描述】:
我需要将一个表导入到一个数组中。并且不是导入所有单元格,而是仅导入 2 列。
例如,来自
| A | B | C | D | F |
|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 |
| 6 | 7 | 8 | 9 | 10 |
到
[
{
'A' => 1,
'F' => 5,
},
{
'A' => 6,
'F' => 10,
}
]
app\Imports\PricesImport.php
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\Importable;
class PricesImport implements ToArray
{
use Importable;
public function array(array $rows)
{
return array($rows[0], $rows[4]);
}
}
以及控制器中的调用:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\PricesImport;
use Maatwebsite\Excel\Facades\Excel;
class SomeController extends Controller
{
public function import(Request $request) {
$array = Excel::toArray(new PricesImport, $request->file('file'));
}
}
但它不起作用。我做错了什么?
更新
尝试了此选项,但它返回所有列,而不是 2 个特定列 app\Imports\PricesImport.php
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\Importable;
class PricesImport implements ToArray
{
use Importable;
private $data;
public function __construct()
{
$this->data = [];
}
public function array(array $rows)
{
foreach ($rows as $row) {
$row = $row->toArray();
$this->data[] = array('sku' => $row[0], 'price' => $row[4]);
}
return $this->data;
}
}
【问题讨论】: