首页 > 解决方案 > 从数组中删除 null

问题描述

我想将 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"
          ]
        ]

非常感谢任何建议。

标签: phplaravel

解决方案


尝试

$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
    )

)

推荐阅读