PHP,从文件中分解数据

PHP,从文件中分解数据,php,explode,Php,Explode,我在从文件中分解数据时遇到了一个问题。 我的文件看起来像 1991年4月21日9:09 58 10004-21-1991年9:09 33 00904-21-1991 9:09 34 01304-21-1991 17:08 62 11904-21-1991 17:08 33 00704-21-1991 我想从中爆炸数据,就像 1991年4月21日9:09 58 100 1991年4月21日9:0933009 1991年4月21日9:09 34013 04-21-1991 17:08 62 119

我在从文件中分解数据时遇到了一个问题。 我的文件看起来像

1991年4月21日9:09 58 10004-21-1991年9:09 33 00904-21-1991 9:09 34 01304-21-1991 17:08 62 11904-21-1991 17:08 33 00704-21-1991

我想从中爆炸数据,就像

1991年4月21日9:09 58 100

1991年4月21日9:0933009

1991年4月21日9:09 34013

04-21-1991 17:08 62 119

04-21-1991 17:08 33 007

到目前为止,我所做的是获得一个数组(数字不同,因为文件不同,但结构相同)

这是我的密码

header("Content-type:text/plain");
  $file = fopen("data/data-03", "r");

$result = array();
    $file = explode("   ", file_get_contents("data/data-03"));
    foreach ( $file as $content ) 
        {
            $result[] = array_filter(array_map("trim", explode("    ", $content)));
        }
    var_dump($result);

这里有一个简单的代码,假设您的初始数据格式不会改变

$str = "04-21-1991 9:09 58 100 04-21-1991 9:09 33 009 04-21-1991 9:09 34 013 04-21-1991    17:08 62 119 04-21-1991 17:08 33 007 04-21-1991";

$result = array();
$result = explode(" ",$str);
$row = 0;

for ($i = 0; $i < sizeof($result)-1; ){
    $arr[$row]["date"] = $result[$i++];
    $arr[$row]["hour"] = $result[$i++];
    $arr[$row]["num"] = $result[$i++];
    $arr[$row]["num2"] = $result[$i++];
    $row++;
}

//check some data:
for ($i = 0; $i < 3; $i++ ){
    echo $arr[$i]["date"] . " ";
    echo $arr[$i]["hour"] . " ";
    echo $arr[$i]["num"] . " ";
    echo $arr[$i]["num2"] . " ";
    echo "<br />";
}
$str=“04-21-1991 9:09 58 100 04-21-1991 9:09 33 009 04-21-1991 9:09 34 013 04-21-1991 17:08 62 119 04-21-1991 17:08 33 007 04-21-1991”;
$result=array();
$result=explode(“,$str”);
$row=0;
对于($i=0;$i”;
}

您可能想尝试使用
preg\u match\u all()
。像这样:

<?php
$string = "04-21-1991 9:09 58 10004-21-1991 9:09 33 00904-21-1991 9:09 34 01304-21-1991 17:08 62 11904-21-1991 17:08 33 00704-21-1991";

preg_match_all("/([\d]{2}-[\d]{2}-[\d]{4}\s[\d]*:[\d]{2}\s[\d]{2}\s[\d]{3})/", $string, $matches);

print_r($matches);

?>

也可以按以下方式处理分解的阵列:

$out = array();

for ( $i=0; $i<count($result); $i++){
    if ( floor($i / 4) == ($i / 4))
        $out[ floor($i / 4) ] = $result[$i];
    $out[ floor($i / 4) ] .= ' '.$result[$i]; 
}
$out=array();

对于($i=0;$iuse而不是explode(),如果每个元素的大小相同explode by“”然后迭代结果并将值分配给数组。请更加注意使输入和输出清晰、对应、缩进良好等。这很可怕。对于结构化断言,按此分组,如果输入包含不同的间距,您可能希望使用
preg_match_all
,而不是粗略的分解。所有答案都是非常好,但是你的最爱。谢谢
Array ( [0] => 04-21-1991 9:09 58 100 [1] => 04-21-1991 9:09 33 009 [2] => 04-21-1991 9:09 34 013 [3] => 04-21-1991 17:08 62 119 [4] => 04-21-1991 17:08 33 007 )
$out = array();

for ( $i=0; $i<count($result); $i++){
    if ( floor($i / 4) == ($i / 4))
        $out[ floor($i / 4) ] = $result[$i];
    $out[ floor($i / 4) ] .= ' '.$result[$i]; 
}