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

时间:2017-05-18 16:04:55

标签: php html arrays multidimensional-array data-extraction

具有格式的文本文件:

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

我正在尝试创建2D数组,首先将其拆分为行,然后按元素拆分为“;”

1 个答案:

答案 0 :(得分:1)

示例输入:

$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

请记住,我只专注于循环内的字符串分割。克里斯&#39;建议处理文件处理。

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