如何分解字符串数组并将结果存储在另一个数组中 (php)

How to explode an array of strings and store results in another array (php)

文本文件格式:

(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;

代码:

<?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??
  }
}
?>

我正在尝试创建二维数组,方法是先拆分成行,然后按“;”拆分元素

示例输入:

$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; ...';

方法#1(不带分号的值存储在数组中):

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','...']
    ]
) */

方法#2(带分号的值存储在数组中):

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;','...']
    ]
) */

这里是demo of both methods.

请记住,我只关注循环内的字符串拆分。 Kris 关于文件处理的建议是可取的。

根据您的环境,您可能需要通过删除 \r 或类似内容来调整第一次爆炸。