Php unset 不删除数组元素

Php Unset not deleting array elements

我正在浏览 csv 文件,并试图删除 2 个数组 (matchingFields &fieldstolookfor) 中的元素,因为我在 csv 中找到了它们的元素。

public function addRecords($dealerFeedsDirectory, $vin)
    {
        $files = glob($dealerFeedsDirectory . "*.csv");
        $fieldsToLookFor = array("dealername", "dealeraddress", "dealerstate", "year", "make", "model", "phone", "url");
        $fieldsFound = array();
        foreach ($files as $file) {
            if(empty($fieldsToLookFor)) {
                break;
            }
            echo "File We are Looking through : " . $file , "<br>";
            echo "Fields left : ";
            print_r($fieldsToLookFor);
            echo " <br>";
            $fp = fopen($file, 'r');
            $csvReader = new CSVReader($fp, ',');
            if ($fieldNames = $csvReader->readHeader()) {
                //print_r( $fieldNames);
                $matchingFields = array();
                foreach ($fieldNames as $fieldName) {
                    if (in_array($fieldName, $fieldsToLookFor)) {
                        $matchingFields[] = $fieldName;
                    }
                }
                //print_r($matchingFields);

                while (($row = $csvReader->readRow()) !== false && !empty($matchingFields)) {
                    if ($row[Constants::VIN] == $vin) {
                        foreach ($matchingFields as $matchingField) {
                            $fieldsFound[$matchingField] = $row[$matchingField];
                            print_r( $matchingFields);echo  "matchingfields <br>";
                            print_r( $fieldsToLookFor);echo  "fieldstolookfor <br>";
                            unset($matchingFields[$matchingField]);
                            unset($fieldsToLookFor[$matchingField]);
                        }
                    break;
                    }
                }
            }
        }
        print_r($fieldsFound);
    }

在检查一个 csv 文件后,项目正在从 $matchingFields 数组中删除,而不是从 $fieldsToLookFor(fieldsToLookfor 也应该有 5 个项目)数组中删除。这是为什么?

Array ( [0] => url [1] => make [2] => model [3] => year [4] => phone ) matchingfields
Array ( [0] => dealername [1] => dealeraddress [2] => dealerstate [3] => year [4] => make [5] => model [6] => phone [7] => url ) fieldstolookfor

有了这个unset:

unset($fieldsToLookFor[$matchingField]);

您正在尝试取消设置 $fieldsToLookFor 数组中的一个键,例如 'model' 或 'url',这是它的值,而不是它的键。 (键为 0、1 等)

事实上,出于同样的原因,您似乎不会从 $matchingFields 中删除项目。这些似乎更有可能是在早期 foreach ($fieldNames as $fieldName) 循环中添加到 $matchingFields 的唯一值。


无需进行大量更改即可完成这项工作的一种简单方法是将字段用作键和值。在外循环之前像这样:

$fieldsToLookFor = array_combine($fieldsToLookFor, $fieldsToLookFor);
foreach ($files as $file){ ...

然后当你设置 $matchingFields:

if (in_array($fieldName, $fieldsToLookFor)) {
    $matchingFields[$fieldName] = $fieldName;
}