一定要有唯一的数组输入

时间:2012-07-03 22:37:25

标签: php arrays unique verification

我有一个包含以下内容的文件:

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

我该怎么做?

6 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:1)

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

答案 2 :(得分:1)

一个简单的方法是使用array_unique,在爆炸后将零件(tab [0]和tab [1])保存到两个单独的数组中,将它们命名为例如$ col1和$ col2然后,你可以做这个简单的测试:

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

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

答案 3 :(得分: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
    }

}

?>

答案 4 :(得分:0)

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

顺便说一句。而不是preg_replace('/[\r\n]+/', "", $tab[1]),请尝试trim(甚至rtrim)。

答案 5 :(得分: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');
相关问题