php – Find data from a txt in array and update

Question:

I'm making a simple code but I can't get it out to see if you could give me a hand please.

I have a .txt file that presents me with the following data:

id|tipo|contador    
id1|0|1
id2|0|1
id1|0|2
...
id20|0|1
id2|0|2
etc...

Code/idea I use but it's not finished, loops are missing etc:

<?php

error_reporting(0);
function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

    $text = file_get_contents('C:\users.txt');
    $exploded = multiexplode(array("|"," ","\n"),$text);

    $id[i] = trim($exploded[0]);
    $type[i] = $exploded[1];
    $count[i] = $exploded[2];
$datos[] = array('id'=>$id[i],'tipo'=>$type[i],'contador'=>$count[i]);
?>

What I need is that when executing the code the txt is read and it makes/updates an array($datos) so that:

  • Each line of the txt corresponds to a new record in the $datos(id,tipo,contador) array.
  • If the id already exists in the array instead of creating a new record increment the contador key of this id by +1 .

I have tried explode and in-array but the truth is that I cannot verify if the id exists and that it works for me because more than 1000 ids can come in the txt and with explode the thing does not work.

Surely there must be another way to do it.
If you can give me a hand please, I'm stuck and oversaturated looking for info in manuals and I don't know. Greetings

Answer:

From what I understand, what you want to do is parsear the content in the txt file, save it in an array with format [id, tipo, contador] and if there is already a record with the same id in the array, we must increment the contador .

To do this you can do it like this:

<?php

// Matriz asociativa para mapear id y posición
$hash = [];
// Arreglo de resultados
$datos = [];

// Obtenemos un arreglo con las líneas del archivo
$lineas = file('C:\users.txt');
foreach ($lineas as $linea) {

    // Extraemos los datos de la línea
    list($id, $tipo, $contador) = explode('|', trim($linea));

    // Si aún no hemos agregado el id al hash
    if (!isset($hash[$id])) {
        // Guardamos en el hash el id y la posicion en el arreglo de datos
        $hash[$id] = count($datos);

        // Guardamos el id en el arreglo de datos
        $datos[] = [
            'id'=>$id,
            'tipo'=>$tipo, 
            'contador'=>$contador,
        ];
    } else {
        // Sumamos al contador del id guardado 1
        $datos[$hash[$id]]['contador']++;
    }
}

var_export($datos);

Demo

Scroll to Top