A
A
Andrew2015-06-08 18:45:50
PHP
Andrew, 2015-06-08 18:45:50

How to check if an entry exists in a CSV file?

Hello, I am parsing a resource, I put the result in a two-dimensional array, then save it in CSV, then I need to check the entries for the presence in this CSV when I reapply, and if there is no specific entry from the parsing result, then add the csv file. The problem is that I tried to try different options, it does not work for me.
I am converting the CSV file to an array, then comparing both arrays.
I tried with array_diff, I wrote my own ... The maximum I achieved was only that the missing entry is determined, if it is at the very end, and if it is in the middle, then nothing works.
Schematically, everything looks like this (only instead of numeric values ​​- strings):

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
            [1] => 6
        )

    [3] => Array
        (
            [0] => 7
            [1] => 8
        )

)
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 5
            [1] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )

)

That is, when comparing these two arrays, it is necessary that this would be returned:
[1] => Array
        (
            [0] => 3
            [1] => 4
        )

Help, please, with a specific code, I have already broken my head ...
UPD: Although there may be another way to compare the lines of the first array with the contents of the CSV file?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2015-06-08
@ntzch

$res = array_udiff($array1, $array2, function($a, $b) {
    if ($a[0] < $b[0]) return -1;
    if ($a[0] > $b[0]) return 1;
    if ($a[1] < $b[1]) return -1;
    if ($a[1] > $b[1]) return 1;
    return 0;
});

But IMHO, it is better to use a database for such a purpose.

S
Stalker_RED, 2015-06-08
@Stalker_RED

Maybe it's easier to take the good old diff ?

D
Denis, 2015-06-08
@prototype_denis

when re-approaching, check the records for the presence in this CSV and if a specific record from the parsing result is missing, then append the csv file.

// $firstArray  = str_getcsv... old
// $secondArray = str_getcsv... new
$mergedArray = array_merge_recursive($secondArray, $firstArray);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question