检查数组行是否为空

时间:2013-08-08 19:20:37

标签: php arrays

我有一个我从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] => 
    )

3 个答案:

答案 0 :(得分:2)

与副本中的内容一样,请查看array_filter

  

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

所以可以用一个简单的行来做到这一点。

if(!array_filter($array)) {
    // Every fields are empty, null or equal to false
}

答案 1 :(得分: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]

答案 2 :(得分: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));
?>