当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Read file and create array with first row as header(keys)

问题描述:

I can read the file and put it into an array.

file.txt:

 time value1 value2

.00 .0000 21.2310

100.92 200.2272 7.7243

200.92 222.4021 8.6395

My current code:

$array = file('file.txt');

$new_array = array();

foreach ($array as $line) {

$string = preg_replace('/\s+/',';', $line);

$line_array = explode("\t", $string);

$new_array[] = $line_array[0];

}

My output:

 array

'time' =>

array

0 => string '.00'

1 => string '267.1081'

2 => string '267.1043'

'value1' =>

array

0 => string '100.92'

1 => string ' 200.2272'

2 => string '7.7243'

'value2' =>

array

0 => string '200.92'

1 => string '222.4021'

2 => string '8.6395'

But the desire I have is:

 $my_array = Array

(

[0] => Array

(

[time] => .00

[value1] => .0000

[value2] => 21.2310

)

[1] => Array

(

[time] => 100.92

[value1] => 200.2272

[value2] => 7.7243

)

[2] => Array

(

[time] => 200.92

[value1] => 222.4021

[value2] => 8.6395

)

)

How can I get the first row as keys for the other values?

网友答案:

This should work for you:

Here I first get the file into an array with file() where every line is one array element. There I ignore new line characters at the end of each line and skip empty lines.

After this I loop through each line with array_map() and split it with preg_split() by 1 or more spaces. And before I return it I remove empty elements with array_filter().

Then I get the first innerArray as $header with array_shift().

At the end I simply go through all innerArrays again and array_combine() the values with the $header array.

<?php

    $lines = file("file.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES);

    $data = array_map(function($v){
        return array_filter(preg_split("/\s+/", $v));
    }, $lines);

    $header = array_shift($data);

    $data = array_map(function($v)use($header){
        return array_combine($header, $v);
    }, $data);

    print_r($data);

?>

output:

Array
(
    [0] => Array
        (
            [time] => .00
            [value1] => .0000
            [value2] => 21.2310
        )

    [1] => Array
        (
            [time] => 100.92
            [value1] => 200.2272
            [value2] => 7.7243
        )

    [2] => Array
        (
            [time] => 200.92
            [value1] => 222.4021
            [value2] => 8.6395
        )

)
分享给朋友:
您可能感兴趣的文章:
随机阅读: