I encountered a problem during exploding data from file. My file looks like
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
I'd like to explode data from it like
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
what i did till now is obtaining an array ( numbers are different, becouse file is different, but structure is the same)
array(1) {
[0]=>
array(901) {
[0]=>
string(10) "07-21-1990"
[1]=>
string(5) "06:43"
[2]=>
string(2) "58"
[3]=>
string(14) "202
07-21-1990"
[4]=>
string(5) "07:03"
[5]=>
string(2) "33"
[6]=>
string(12) "4
07-21-1990"
and here is my code
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);
You might want to try using preg_match_all()
. Like so:
<?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);
?>
The above code will output:
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 )
Here's a simple code of doing that, assuming your initial data format won't change.
$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 />";
}
you could also process the exploded array in the following way:
$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];
}
you could replace ' ' with the seperator you want, I assumed a simple space.
It is basicly always concatenating 4 entries of the array resulting from your explosion, and adds them to a new array. You could also fetch the results in a new String and just add a after every 4th entry in the same way, if that is what you desire.