PHP和array_slice中两个字符串的比较

时间:2012-11-28 03:05:11

标签: php csv string-comparison slice

我觉得我做的事情非常愚蠢,但我无法理解它是什么 我正在运行由fgetcsv()生成的数组数组。我想要的是在一行中的值与下一行中的值不同的位置将数组分成两部分 此代码导致$first保存除一个数组之外的所有数组,而$second保持最后一个 - 完全忽略字符串比较。 strcmp()导致同样的事情。

$csv = array();
$file = fopen('A.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}
fclose($file);

array_shift($csv); //gets rid of the CSV headers
$rows = count($csv);

for ($i = 0; $i <= $rows; $i++){
    if ($csv[$i][1] != $csv[$i+1][1]){
        $first = array_slice($csv, 0, $i);
        $second = array_slice($csv, $i);
    }
}

以下是CSV文件的示例:

NAME,MATCHNAME,CHROMOSOME,START LOCATION,END LOCATION,CENTIMORGANS,MATCHING SNPS
A,person_one,2,20945970,23287731,2.48,500
A,person_one,2,233444593,234432885,1.56,500
A,person_one,4,99184637,100861136,1.24,500
A,person_two,1,154990798,157871980,2.8,700 //Here's where the new array should start
A,person_two,1,67136078,70785393,2.28,800

编辑:此示例的预期$first为:

Array
(
[0] => Array
    (
        [0] => A
        [1] => person_one
        [2] => 2
        [3] => 20945970
        [4] => 23287731
        [5] => 2.48
        [6] => 500
    )

[1] => Array
    (
        [0] => A
        [1] => person_one
        [2] => 2
        [3] => 233444593
        [4] => 234432885
        [5] => 1.56
        [6] => 500
    )

[2] => Array
    (
        [0] => A
        [1] => person_one
        [2] => 4
        [3] => 99184637
        [4] => 100861136
        [5] => 1.24
        [6] => 500
    )
)

我的预期$second将是:

Array
(
[0] => Array
    (
        [0] => A
        [1] => person_two
        [2] => 1
        [3] => 154990798
        [4] => 157871980
        [5] => 2.8
        [6] => 700
    )

[1] => Array
    (
        [0] => A
        [1] => person_two
        [2] => 1
        [3] => 67136078
        [4] => 70785393
        [5] => 2.28
        [6] => 800
    )
)

1 个答案:

答案 0 :(得分:1)

它正在做你想要的,但当它到达最后一次迭代时,它会将最后一行中的任何内容与null进行比较,因此它会覆盖$first$second

尝试在分配后添加break;,以便在满足条件时突破循环。