0

我有一个从 csv 导入的数组。但是 csv 的最后一行是 epmty,但它仍然将空值导入到数组中。

有没有一种简单的方法来检查数组中的整行是否为空?

这是我正在使用的代码(我正在根据另一个数组的内容检查该数组以构建一个 mySQL 语句:

foreach (array_keys($array[0]) as $arraykey => $dbtitles){
            foreach ($fields as $dbkey => $dbfield){
                if ($dbtitles == $dbfield && !empty($arraykey) ){
                    $insertSQL .= "student_" . $dbkey . ", ";
                }
            }
        }

抱歉,如果我是愚蠢的。

这是我的数组的最后一部分:

[21] => Array
    (
        [Username] => 
        [Last_Name] => Jones
        [First_Name] => Tom
        [Email] => 
        [Password] => password
        [Student_Id] => 
        [Middle_Name] => 
        [Job_Title] => 
        [Department] => 
        [Company] => 
        [Street_1] => 21 A Road
        [Street_2] => 
        [City] => Exeter
        [County] => 
        [Postcode] => EX1 1AA
        [Country] => 
        [Work_Phone] => 
        [Home_Phone] => 
        [Work_Fax] => 
        [Mobile_Phone] => 07111 222333
        [Website] => 
        [Role] => Exeter City
    )

[22] => Array
    (
        [Username] => 
        [Last_Name] => 
        [First_Name] => 
        [Email] => 
        [Password] => 
        [Student_Id] => 
        [Middle_Name] => 
        [Job_Title] => 
        [Department] => 
        [Company] => 
        [Street_1] => 
        [Street_2] => 
        [City] => 
        [County] => 
        [Postcode] => 
        [Country] => 
        [Work_Phone] => 
        [Home_Phone] => 
        [Work_Fax] => 
        [Mobile_Phone] => 
        [Website] => 
        [Role] => 
    )
4

3 回答 3

2

就像副本中所说的那样,看看array_filter

如果没有提供回调,则所有等于 FALSE 的输入条目(请参阅转换为布尔值)都将被删除。

所以可以在一个简单的行中做到这一点。

if(!array_filter($array)) {
    // Every fields are empty, null or equal to false
}
于 2013-08-08T19:24:51.247 回答
0
foreach (array_keys($array[0]) as $arraykey => $dbtitles){
        foreach ($fields as $dbkey => $dbfield){
            if ($dbtitles == $dbfield && !empty($arraykey) ){
                $insertSQL .= "student_" . $dbkey . ", ";
            }
        }
    }

在您的 foreach 中,您只能找到数组 [0] 的数组键,请尝试仅使用 $array 而不是 $array[0]

于 2013-08-08T19:25:01.627 回答
0

您应该尝试 array_pop 以获得更好的解决方案。

<?php
$CSVFileLines = array_pop(file('/path/to/your/data.csv'));
foreach($CSVFileLines as $CSVLine){
$CSVLineValues = array_map('mysql_real_escape_string', explode(',', $CSVLine));
$InsertSQL = sprintf("insert into tablename values ('%s')", implode("','", $CSVLineValues));
mysql_query($InsertSQL); #Depreated in All recent PHP Versions so you should use MySQLi
}
echo sprintf('There were %s lines contained in the targeted CSV.', count($CSVFileLines));
?>
于 2013-08-08T19:33:27.310 回答