Build associative array with txt lines

2

Hi, I have a txt that has the following structure

[HEADER]
7894=12.01
1124=456
2234=1.0
2222=2.3
[DATAOUT]
1235=7
1006=10.0
1007=10
[ENDOFFILE]

I'm reading it from PHP like this:

$archivo = fopen('archivo.txt','r');
$data_archivo=array();
while ($linea= fgets($archivo)) {
            $data_archivo[] = $linea;
}

Now I go to that array like this:

$data_final=array();
foreach ($data_archivo as $d) {
 $valor=substr($dato,6,20);
 $codigo=substr($dato,0,5);
if ($codigo=='7894' || $codigo=='1124', etc.){
$data_final=$valor;
}
}

returns an array 0 => 12, 1 => 0.1 etc

What I would like is to assemble an associative array

{'a' => 12, 'b' => 0.1, etc.}

    
asked by frijjolitto 27.04.2018 в 22:47
source

1 answer

1

You could use the code as a key in this way:

$data_final=array();
foreach ($data_archivo as $d) {
  $valor=substr($dato,6,20);
  $codigo=substr($dato,0,5);
  if ($codigo=='7894' || $codigo=='1124', etc.){
    $data_final[$codigo]=$valor;
  }
}
    
answered by 27.04.2018 / 22:52
source