2 回答

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
問題是在循環(huán)中使用 unset() 。在下一次迭代中,索引不再與您使用 unset() 破壞數(shù)組之前的索引相同。有時,您可以使用 array_values() 來處理這個問題,但在這種情況下,只構(gòu)建第二個僅包含您想要的值的數(shù)組會更簡單。以下代碼有效。我使用 array_values() 只是為了獲取您提供的字符串并使索引恢復(fù)正常。
也就是說,由于“前 2 個元素之前已使用 unset 刪除”,因此您需要在到達(dá)此部分之前對數(shù)組運行 array_values() 。
<?php
$str ='{"8":"2020-06-L-1.txt","9":"2020-06-L-2.txt","10":"2020-06-L-3.txt","11":"2020-06-L-4.txt","12":"2020-06-L-5.txt","15":"2020-06-N-3.txt","16":"2020-06-N-4.txt","17":"2020-06-N-5.txt","18":"2020-06-N-6.txt","19":"2020-06-O-1.txt","20":"2020-06-O-2.txt","21":"2020-06-O-3.txt","22":"2020-06-O-4.txt","23":"2020-06-S-1.txt","24":"2020-06-S-2.txt","25":"2020-06-S-3.txt"}';
$fileArray = json_decode($str, true);
$fileArray = array_values($fileArray);
echo '<p>fileArray: ';
var_dump($fileArray);
echo '</p>';
function fileFilter() {
global $fileArray, $fileFilterPattern;
$filteredArray = [];
for ($j = 0; $j < count($fileArray); $j++) {
if(preg_match($fileFilterPattern, $fileArray[$j]) === 1) {
//unset($fileArray[$j]);
array_push($filteredArray, $fileArray[$j]);
}
}
echo '<p>filteredArray: ';
var_dump($filteredArray);
echo '</p>';
//return;
}
$month =='';
$year = '';
// If user does not provide a filter value, it gets converted into wildcard symbol
if ($month == '') {
$month = '..';
}
if ($year == '') {
$year = '....';
}
if ($section == '') {
$section = '.';
}
$section = 'L';
$fileFilterPattern = "#{$year}-{$month}-{$section}-.\.txt#";
echo '<p>fileFilterPattern: ';
var_dump($fileFilterPattern);
echo '</p>';
/* function only runs if user applied at least one filter */
if (!($month == '..' && $year == '....' && $section == '.')) {
fileFilter();
}
?>

TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
主要問題是count每次減少unset,所以你應(yīng)該定義一次計數(shù)。假設(shè)-1和$j = 2對于您的場景是正確的:
$count = count($fileArray) - 1;
for ($j = 2; $j < $count; $j++) {
if(!(preg_match($fileFilterPattern, $fileArray[$j]))) {
unset($fileArray[$j]);
}
}
還有其他方法,您不必假設(shè)然后跟蹤密鑰:
foreach($fileArray as $k => $v) {
if(!preg_match($fileFilterPattern, $v)) {
unset($fileArray[$k]);
}
}
我會擺脫你的fileFilter功能并改用這個方便的功能,它將返回與模式匹配的所有項目:
$fileArray = preg_grep($fileFilterPattern, $fileArray);
- 2 回答
- 0 關(guān)注
- 248 瀏覽
添加回答
舉報