从数组中删除null

时间:2019-10-24 09:53:48

标签: php laravel

我想将csv导入数据库,但是我怎么得到此错误: 代码: ErrorException array_combine():两个参数应具有相等数量的元素 我知道错误显示两个数组的长度相同,但是我找不到从数组中删除空值的解决方案     

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Accounts;
class AccountController extends Controller
{
    public function show(){
        return view ('upload');
    }
    public function store(Request $request){


        $file = $request->file('upload-file');
        $csvData = file_get_contents($file);

        $rows = array_map("str_getcsv", explode("\n", $csvData));

        dd($rows);
        $header = array_shift($rows);

        foreach ($rows as $row) {


            $row = array_combine($header, $row);



            set_time_limit(0);
            Accounts::create([
                'AccountClass' => $row['Classe'],
                'AccountNumber' => $row['Compte'],
                'AccountDesc' => $row['Desc'],
                'active' => 1,
            ]);
        }

        return view ('home');

    }

}

结果: 标头:

array:3 [▼
  0 => "Classe"
  1 => "Compte"
  2 => "Desc"
]

行:

   array:4 [▼
      0 => array:3 [▼
        0 => "1"
        1 => "1"
        2 => "COMPTES DE FINANCEMENT PERMANENT"
      ]
      1 => array:3 [▼
        0 => "1"
        1 => "11"
        2 => "CAPITAUX PROPRES"
      ]
      2 => array:1 [▼
        0 => null
      ]
    ]

但是我想要

   array:4 [▼

          0 => array:3 [▼
            0 => "1"
            1 => "1"
            2 => "COMPTES DE FINANCEMENT PERMANENT"
          ]
          1 => array:3 [▼
            0 => "1"
            1 => "11"
            2 => "CAPITAUX PROPRES"
          ]
        ]

任何建议都非常感谢。

2 个答案:

答案 0 :(得分:2)

尝试

$res = [];
foreach($x as $key => $value)
{
if($value[0] == null)
unset($x[$key]);
else
$res[$key] = $value;
}
print_r($res);

输出将为

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 1
        [2] => COMPTES DE FINANCEMENT PERMANENT
    )

[1] => Array
    (
        [0] => 1
        [1] => 11
        [2] => CAPITAUX PROPRES
    )

)

答案 1 :(得分:1)

由于laravel已在此问题上加了标签,所以我建议使用collection

$array = [1, 2, 3, null, 4];
$array = collect($array)->filter()->values()->toArray();

在这里, filter()将删除 null 值,而 value()重新索引您的数组。
希望能帮助到你。干杯。