将.txt文件分解为多维数组

时间:2012-09-16 18:02:29

标签: php arrays multidimensional-array

目前我的文件看起来像这样:

Awesomedude123 = 399,408 = September 16, 2012:
Username11 = 1,914,144 = September 16, 2012:
EpicSurfer = 1,031,427 = September 16, 2012:

我想要做的是用PHP将其转换为多维数组,所以它看起来像这样:

Array
(
    [1] => Array
    (
        [0] => Awesomedude123
        [1] => 399,408
        [2] => September 16, 2012
    )

[2] => Array
    (
        [0] => Username11
        [1] => 1,914,144
        [2] => September 16, 2012
    )

[3] => Array
    (
        [0] => EpicSurfer
        [1] => 1,031,427
        [2] => September 16, 2012
    )

)

我尝试过使用array_shift,但它没有用完。任何帮助都将非常感激!

2 个答案:

答案 0 :(得分:2)

以下是代码:

<?php

$data = file_get_contents('File.txt'); // Get the file content
$data = str_replace(array("\n", "\r"), '', $data); // Clear newline characters

$data = explode(':', $data); // Get each record by : at end of line

unset($data[count($data) - 1]); // Clear the last empty element

$final_array = array();
foreach($data AS $row){ // Loop the exploded data
    $final_array[] = explode(' = ', $row); // Explode each row by Space=Space to each row of final_array
}

print_r($final_array);

?>

答案 1 :(得分:2)

您可以使用正则表达式来拆分字符串:

myarray = array();
$file = fopen("myfile",'r');
while (!feof($file)) {
  $line = fgets($file);
  preg_match("/(\w+) = (.+) = (.+)/",$line,$matches);
  myarray[] = array($matches[1],$matches[2],$matches[3]);
}