kincur kincur - 5 months ago 21
PHP Question

Creating an array from a input from text file having 4 columns

I stuck with problem of creating one array of 4 different arrays.
I need one array with values to create graph of it... Now I'm getting 4 arrays with string.
The data is 4 column with Time, ax ay az position and header. I'm removing header and names of the columns first. The data looks like:

ID_PATIENT, ID_MOVE, NAME, SURNAME

TIME aX aY aZ

713 -620 -2228 15832

755 -596 -2204 15804

797 -596 -2176 15876

838 -584 -2072 15808

880 -484 -2224 15988

921 -676 -2180 15892

963 -532 -2128 15944

Here you have sample of my code, which parsing data from .txt file:

<?php

session_start();

echo $_POST['name'];

$filee= $_POST['name'];

echo "<br>";

$file = "data/".$filee;


$Time=array();
$aX=array();
$aY=array();
$aZ=array();

$lines = file($file);


for($i=0; $i<2; ++$i) {
$which=$i;
unset($lines[$which--]);
$filee=fopen($lines,'w');
fwrite($filee,join('',$lines));
fclose($filee);
}

foreach($lines as $line)
{
list( $Timetmp, $aXtmp, $aYtmp, $aZtmp) = split("\t", $line );
array_push($Time, $Timetmp);
array_push($aX, $aXtmp);
array_push($aY, $aYtmp);
array_push($aZ,$aZtmp);
}

foreach($Time as $indice => $valor)
print "$valor <br>";

echo "....<BR>";

foreach($aX as $indice => $valor)
print "$valor <br>";

echo "....<BR>";

foreach($aY as $indice => $valor)
print "$valor <br>";

echo "....<BR>";


foreach($aZ as $indice => $valor)
print "$valor <br>";


?>

Answer

You should create an associative array for a better representation of your data :

In your code you can do following modifications:

$processedArray = array();    
foreach($lines as $line)
    {
    list( $Timetmp, $aXtmp, $aYtmp, $aZtmp) = split("\t", $line );
    $processedArray[] = array("time"=>$Timetmp,"ax"=>$aXtmp,"ay"=>$aYtmp,"az"=>$aZtmp);
    }

Output:

array(
      array("time"=>713,"ax"=>-620,"ay"=>-2228,"az"=>15832),
      array("time"=>755,"ax"=>-596,"ay"=>-2204,"az"=>15804),
      ....,
      ....
)