确保具有唯一的数组条目。

3

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

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]中包含的数据都是唯一的。
例如,如果文件如下,我希望抛出一个"throw new Exception":
toto;145
titi;7
tutu;7
tata;28

或者像这样:
toto;145
tata;7
tata;28

我该怎么做呢?
6个回答

2

使用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;
    }
}

我最终使用了您的代码,只是稍微做了一些改动以便于调试。 - Bellami
如果(array_key_exists($key, $tab)) { echo "包含<strong>".$key."</strong>的第一行是重复的!!!!"; throw new Exception("Error Processing Request", 1); } else if (in_array($val, $tab)) { echo "包含<strong>".$val."</strong>的第一行是重复的!!!!"; throw new Exception("Error Processing Request", 1); } - Bellami

1

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


1

一个简单的方法是使用array_unique,在你执行explode操作后将其部分(tab[0]和tab[1])保存到两个不同的数组中,例如命名为$col1和$col2,然后你可以进行这个简单的测试:

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

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


0

使用具有键“toto”、“tata”等的关联数组。
要检查键是否存在,您可以使用array_key_existsisset

顺便说一句。与其使用preg_replace('/[\r\n]+/', "", $tab[1]),不妨尝试一下trim(甚至rtrim)。


0

在遍历数组时,将值添加到现有的数组中,即占位符,该占位符将通过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
    }

}

?>

0
//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');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接