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

99封情书 提交于 2019-12-11 02:29:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44052754/how-to-explode-an-array-of-strings-and-store-results-in-another-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!