Skip to content
Advertisement

PHP find similar ID’s (EAN codes) and show if excist

I have a database with different kind of products that have similar ID’s (EAN codes). I’m trying to print a list of all similar codes so I can import them and connect them to the same product.

Example:

Product Y has ID 190198001795 and 0190198001795

Product X has ID 190198001780, 0190198001780 and 00190198001780

What I’m trying to achieve:

190198001795 – 0190198001795 190198001795 – 0190198001780 – 00190198001780

What did I try: Create a foreach to ‘group’ the similar ID’s, but eventually this may corrupt the correct groups.

<?

// GET ALL PRODUCT ID's

$sql = "SELECT * FROM `products`";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        // Total Downloads - Thousand sperator
        $shopID = $row["id"];
        $EAN = $row["ean"];

        $sqlDouble = "SELECT * FROM `products` WHERE `EAN` IN ('$EAN','0$EAN','00$EAN','000$EAN') LIMIT 200";
        $resultDouble = $mysqli->query($sqlDouble);

        if ($resultDouble->num_rows > 1) {
            // output data of each row
            while($row = $resultDouble->fetch_assoc()) {

              $EAN = $row["ean"];
              $shopID = $row["id"];
              $children[] = $EAN;
          }

        }

      }
}


foreach (array_chunk($children, 2, true) as $array) {
    echo '<div>';
    foreach($array as $kicks) {
         echo $kicks." ";
    }
    echo '</div>';
}



?>

Is there another way to parse trough my rows and check / combine similar ID’s?

Advertisement

Answer

Try this. See comments for explanation. Outputs:

array(2) {
  [190198001780]=>
  array(2) {
    [2]=>
    string(13) "0190198001780"
    [8]=>
    string(14) "00190198001780"
  }
  [1234]=>
  array(2) {
    [5]=>
    string(5) "01234"
    [6]=>
    string(6) "001234"
  }
}

Code:

<?php

$eans = ['190198001780', '8715839583923', '0190198001780', '015839583923', '1234', '01234', '001234', '001235', '00190198001780'];

foreach ($eans as $ean)
{
    // For all EANs that do not have a leading zero, try to find
    // similar ones by looking for the same code with one or more leading
    // zeroes.
    if ($ean[0] !== '0' && ctype_digit($ean))
    {
        // Look for any occurrences of this EAN with one or more (+) leading zeroes.
        // If no similar EANs found, then don't record any.
        if ($matches = preg_grep('/[0]+' . $ean . '/', $eans))
            $children[$ean] = $matches;
    }
}

var_dump($children);
/*
array(2) {
  [190198001780]=>
  array(2) {
    [2]=>
    string(13) "0190198001780"
    [8]=>
    string(14) "00190198001780"
  }
  [1234]=>
  array(2) {
    [5]=>
    string(5) "01234"
    [6]=>
    string(6) "001234"
  }
}
*/
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement