确保具有唯一的阵列条目


Be sure to have unique array entry

我有一个文件,其中包含以下内容:

toto;145
titi;7
tata;28

我分解这个文件以拥有一个数组。我能够使用该代码显示数据:

foreach ($lines as $line_num => $line) {
    $tab = explode(";",$line);
    //erase return line
    $tab[1]=preg_replace('/['r'n]+/', "", $tab[1]);
    echo $tab[0]; //toto //titi //tata
    echo $tab[1]; //145 //7 //28
}

我想确保每个$tab[0]$tab[1]中包含的数据都是唯一的。

例如,如果文件如下所示,我想要一个"抛出新异常":

toto;145
titi;7
tutu;7
tata;28

或类似:

toto;145
tata;7
tata;28

我该怎么做?

使用 file() 将文件转换为数组,并通过额外的重复检查转换为关联数组。

$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$tab = array();
foreach ($lines as $line) {
    list($key, $val) = explode(';', $line);
    if (array_key_exists($key, $tab) || in_array($val, $tab)) {
        // throw exception
    } else {
        $tab[$key] = $val;
    }
}
将它们

存储为数组中的键=>值对,并在循环文件时检查数组中是否已存在每个键或值。 您可以使用 array_key_exists 检查现有键,并使用 in_array 检查现有值。

一个简单的方法是使用array_unique,在爆炸后将部分(tab[0]和tab[1])保存到两个单独的数组中,将它们命名为例如$col 1和$col 2,然后,您可以执行以下简单测试:

<?php
if (count(array_unique($col1)) != count($col1))
echo "arrays are different; not unique";
?>

如果存在重复的条目,PHP 会将您的数组部分变成唯一的,因此如果新数组的大小与原始数组不同,则意味着它不是唯一的。

//contrived file contents
$file_contents = "
toto;145
titi;7
tutu;7
tata;28";
//split into lines and set up some left/right value trackers
$lines = preg_split('/'n/', trim($file_contents));
$left = $right = array();
//split each line into two parts and log left and right part
foreach($lines as $line) {
    $splitter = explode(';', preg_replace('/'r'n/', '', $line));
    array_push($left, $splitter[0]);
    array_push($right, $splitter[1]);
}
//sanitise left and right parts into just unique entries
$left = array_unique($left);
$right = array_unique($right);
//if we end up with fewer left or right entries than the number of lines, error...
if (count($left) < count($lines) || count($right) < count($lines))
    die('error');

使用带有键 "toto"、"tata" 等的关联数组。
要检查密钥是否存在,您可以使用 array_key_exists 或 isset。

顺便说一句。与其preg_replace('/['r'n]+/', "", $tab[1]),不如尝试修剪(甚至修剪)。

当您遍历数组时,将值添加到现有数组中,即占位符,该数组将用于通过 in_array() 检查该值是否存在。

<?php
$lines = 'toto;145 titi;7 tutu;7 tata;28';
$results = array();
foreach ($lines as $line_num => $line) {
    $tab = explode(";",$line);
    //erase return line
    $tab[1]=preg_replace('/['r'n]+/', "", $tab[1]);
    if(!in_array($tab[0]) && !in_array($tab[1])){
        array_push($results, $tab[0], $tab[1]);
    }else{
        echo "value exists!";
        die(); // Remove/modify for different exception handling
    }
}
?>