這裏是一個解決方案,應輸出新索引數組。
$result = array_deflate(explode($delim, $array));
function array_deflate($arr, $emptyval=''){
$ret=[];
for($i=0,$L=count($arr); $i<$L; ++$i)
if($arr[$i] !== $emptyval) $ret[]=$arr[$i];
return $ret;
}
儘管與其他一些建議非常相似,但該實現具有通用性。對於包含非字符串元素的數組,請提供一個類型化的空值作爲第二個參數。
array_deflate($objArray, new stdClass());
array_deflate($databaseArray, NULL);
array_deflate($intArray, NULL);
array_deflate($arrayArray, []);
array_deflate($assocArrayArray, [''=>NULL]);
array_deflate($processedArray, new Exception('processing error'));
。
。
。
使用可選的過濾器參數..
function array_deflate($arr, $trigger='', $filter=NULL, $compare=NULL){
$ret=[];
if ($filter === NULL) $filter = function($el) { return $el; };
if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };
for($i=0,$L=count($arr); $i<$L; ++$i)
if(!$compare(arr[$i],$trigger)) $ret[]=$arr[$i];
else $filter($arr[$i]);
return $ret;
}
隨着使用..
function targetHandler($t){ /* .... */ }
array_deflate($haystack, $needle, targetHandler);
車削array_deflate成處理的選擇元件的方式和從陣列中除去它們。更好的方法是把if語句變成一個比較函數,這個函數也可以作爲一個參數傳遞,以防你喜歡。
array_inflate
是相反的,因爲匹配的第一個參數被推送到非匹配被過濾,所以需要一個額外的數組。
function array_inflate($dest,$src,$trigger='', $filter=NULL, $compare=NULL){
if ($filter === NULL) $filter = function($el) { return $el; };
if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };
for($i=0,$L=count($src); $i<$L; ++$i)
if($compare(src[$i],$trigger)) $dest[]=$src[$i];
else $filter($src[$i]);
return $dest;
}
隨着使用..
$smartppl=[];
$smartppl=array_inflate($smartppl,
$allppl,
(object)['intelligence'=>110],
cureStupid,
isSmart);
function isSmart($a,$threshold){
if(isset($a->intellgence)) //has intelligence?
if(isset($threshold->intellgence)) //has intelligence?
if($a->intelligence >= $threshold->intelligence)
return true;
else return INVALID_THRESHOLD; //error
else return INVALID_TARGET; //error
return false;
}
function cureStupid($person){
$dangerous_chemical = selectNeurosteroid();
applyNeurosteroid($person, $dangerous_chemical);
if(isSmart($person,(object)['intelligence'=>110]))
return $person;
else
lobotomize($person);
return $person;
}
從而爲全球教育問題的理想算法。 Aaand我會在我把它變成別的東西之前停下來。
我認爲這是最正確的,因爲它維護正確的數組索引。 – 2008-09-15 17:18:59
@Ryono:你究竟是什麼意思? – 2008-10-30 15:17:45
preg_split將返回一個具有順序數組索引的數組(即0,1,2,3)。其他一些使用array_filter的建議將會返回非連續的數組索引,因爲一些元素被過濾掉了,並且剩下像0,1,3,7這樣的數組索引。 – 2009-08-18 16:23:50