php - 从数组中删除 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"
]
]
非常感谢任何建议。
解决方案
尝试
$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
)
)
推荐阅读
- java - 我的 AdMob 广告未在 android studio 中展示
- scala - sbt 测试因“分叉测试工具失败”而失败
- ios - SciCharts - ISCIAxisCore 可见的最小和最大索引
- python - JSON TypeError:字符串索引必须是整数
- python - 如何根据 Django 中的 UserGroup 显示不同的内容?
- python - 正则表达式匹配一个包含任何两位整数的特定字符串?
- eslint - eslint 不遵循 vue/* 的规则
- postgresql - 将数据更新到数组列 Postgres
- python - 在Python中启动各种动态进程
- java - 如何在二叉树中找到一个值