从具有4列的文本文件的输入创建数组

时间:2016-06-14 17:54:40

标签: php arrays parsing

我遇到了创建一个包含4个不同数组的数组的问题。 我需要一个带有值的数组来创建它的图形...现在我得到4个带字符串的数组。 数据是4列,带有Time,ax ay az position和header。我先删除列的标题和名称。数据如下:

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

这里有我的代码示例,它解析来自.txt文件的数据:

<?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>"; 


 ?>

1 个答案:

答案 0 :(得分:0)

您应该创建关联数组以更好地表示数据

在您的代码中,您可以进行以下修改:

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

<强>输出:

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