3

Have text file in format:

(400, 530); 6.9; 5.7; 5.0;//------> continues for 100 values.

(500, 530); 7.9; 5.1; 5.0;

(600, 530); 6.7; 6.7; 7.2;

Code:

<?php
$file="./Speed10.asc";
$document=file_get_contents($file);
$rows = explode ('(', $document); //splits document into rows

foreach ($rows as &$rowvalue) {
     explode (';', $rowvalue);<----- How to assign each of these to member 
                                     of an array??
  }
}
?>

I'm trying to create 2D array, by splitting first into rows, then by element split by ';'

MRDJR97
  • 818
  • 2
  • 10
  • 27

1 Answers1

2

Sample Input:

$document='(400, 530); 6.9; 5.7; 5.0; ...
(500, 530); 7.9; 5.1; 5.0; ...
(600, 530); 6.7; 6.7; 7.2; ...';

Method #1 (values without semi-colons stored in array):

foreach(explode("\r\n",$document) as $row){   // split the content by return then newline
    $result[]=explode("; ",$row);             // split each row by semi-colon then space
}
var_export($result);
/* Output:
    [
        ['(400, 530)','6.9','5.7','5.0','...'],
        ['(500, 530)','7.9','5.1','5.0','...'],
        ['(600, 530)','6.7','6.7','7.2','...']
    ]
) */

Method #2 (values with semi-colons stored in array):

foreach(explode("\r\n",$document) as $row){    // split the content by return then newline
    $result[]=preg_split('/(?<!,) /',$row);    // split each row by space not preceeded by comma
}
var_export($result);
/* Output:
    [
        ['(400, 530);','6.9;','5.7;','5.0;','...'],
        ['(500, 530);','7.9;','5.1;','5.0;','...'],
        ['(600, 530);','6.7;','6.7;','7.2;','...']
    ]
) */

Here is demo of both methods.

Keep in mind I am only focusing on the string splitting inside the loop. Kris' advice on file handling is advisable.

Depending on your environment, you may need to adjust the first explode by removing \r or similar.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136