我试图做一个脚本来从我的数组中删除任何空元素。删除阵列中的[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>
尝试[ array_shift()](http://www.php.net/manual/en/function.array-shift.php)删除第一个元素 – 2012-08-08 20:08:42
我会在其中添加一个额外的函数来检查值是否为“ 0“然后使用这个。 – 2012-08-08 20:10:15
[删除空数组元素]可能的重复(http://stackoverflow.com/questions/3654295/remove-empty-array-elements) – 2012-08-08 20:10:42