2012-08-08 216 views
0

我試圖做一個腳本來從我的數組中刪除任何空元素。刪除陣列中的[0]元素,而不刪除整個陣列

然而,一個空的元素在[0]插槽中,所以當我取消設置值時,它會刪除我的整個數組。至少我認爲這就是發生了什麼,爲什麼這不起作用?

<?php 

$idfile = file_get_contents("datafile.dat"); 
$idArray = explode("\n", $idfile); 
print_r($idArray); 
foreach ($idArray as $key => &$value) { 
    echo "Key is: ".$key." and value is: ".$value."<br />\n"; 
    if ($value == ""){ 
     echo "Killing value of ".$value."<br />"; 
     unset($value[$key]); 
    } 
    $value = str_replace("\n", "", $value); 
    $value = str_replace("\r", "", $value); 
    $value = $value.".dat"; 
} 

print_r($idArray); 
?> 

下面是輸出:

Array 
(
    [0] => 
    [1] => test1 
    [2] => test2 
) 
Key is: 0 and value is: <br> 
Killing value of <br> 
+1

嘗試[ array_shift()](http://www.php.net/manual/en/function.array-shift.php)刪除第一個元素 – 2012-08-08 20:08:42

+0

我會在其中添加一個額外的函數來檢查值是否爲「 0「然後使用這個。 – 2012-08-08 20:10:15

+0

[刪除空數組元素]可能的重複(http://stackoverflow.com/questions/3654295/remove-empty-array-elements) – 2012-08-08 20:10:42

回答

4

如果你只是刪除空值嘗試使用unset($idArray[$key])代替。如果你只是想整體刪除的第一個元素,使用array_shift()

+0

我剛剛意識到我有多少白癡 - 我試圖刪除$值[ $ key]而不是你所說的。哈,我需要睡覺。 – 2012-08-08 20:12:49

1

另外一個不錯的解決辦法是使用array_filter()方法,它將處理迭代和返回濾波陣列爲您提供:

<?php 

function isNotEmpty($str) 
{ 
    return strlen($str); 
} 

$idfile = file_get_contents("datafile.dat"); 
$idArray = explode("\n", $idfile); 
$idArray = array_filter($idArray, "isNotEmpty"); 

?>