将文本文件读入数组

时间:2018-05-05 02:43:34

标签: php arrays

我希望将基于文本的DAT文件转换为PHP中的数组。通常我会读取每一行并将其分解为一个数组,但这个文件是不同的。

[0]
FirstRideOn=43169.5701090972
Laps=4591
LastRideOn=43224.7924173611
Name=Standard 1
Nr=1
ResetDate=0
RunningTime=2481
Runs=233
TranNr=7435191

[1]
FirstRideOn=43149.5406271644
Laps=5528
LastRideOn=43224.7616565972
Name=Standard 2
Nr=2
ResetDate=0
RunningTime=2957
Runs=292
TranNr=8377256

我希望将它加载到关联数组中。

非常感谢任何反馈或建议!

1 个答案:

答案 0 :(得分:0)

您的问题并不清楚您希望数组的格式是什么。所以这里有两种选择。首先,我们将文件读入数组:

$input= file('somefile.dat', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

然后我们可以处理数组来创建一个关联数组。这是第一个选择:

$output = array();
foreach ($input as $line) {
    if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
        $entry = (int)$matches[1];
        $output[$entry] = array();
    }
    else {
        list($key, $value) = explode('=', $line);
        $output[$entry][$key] = $value;
    }
}
print_r($output);

生成此输出:

Array
(
    [0] => Array
        (
            [FirstRideOn] => 43169.5701090972
            [Laps] => 4591
            [LastRideOn] => 43224.7924173611
            [Name] => Standard 1
            [Nr] => 1
            [ResetDate] => 0
            [RunningTime] => 2481
            [Runs] => 233
            [TranNr] => 7435191
        )

    [1] => Array
        (
            [FirstRideOn] => 43149.5406271644
            [Laps] => 5528
            [LastRideOn] => 43224.7616565972
            [Name] => Standard 2
            [Nr] => 2
            [ResetDate] => 0
            [RunningTime] => 2957
            [Runs] => 292
            [TranNr] => 8377256
        )
)

或者我们可以这样做:

// alternate style
$output = array();
foreach ($input as $line) {
    if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
        $entry = (int)$matches[1];
    }
    else {
        list($key, $value) = explode('=', $line);
        if (!array_key_exists($key, $output)) $output[$key] = array();
        $output[$key][$entry] = $value;
    }
}
print_r($output);

生成此输出。选择权在你手中!

Array
(
    [FirstRideOn] => Array
        (
            [0] => 43169.5701090972
            [1] => 43149.5406271644
        )

    [Laps] => Array
        (
            [0] => 4591
            [1] => 5528
        )

    [LastRideOn] => Array
        (
            [0] => 43224.7924173611
            [1] => 43224.7616565972
        )

    [Name] => Array
        (
            [0] => Standard 1
            [1] => Standard 2
        )

    [Nr] => Array
        (
            [0] => 1
            [1] => 2
        )

    [ResetDate] => Array
        (
            [0] => 0
            [1] => 0
        )

    [RunningTime] => Array
        (
            [0] => 2481
            [1] => 2957
        )

    [Runs] => Array
        (
            [0] => 233
            [1] => 292
        )

    [TranNr] => Array
        (
            [0] => 7435191
            [1] => 8377256
        )

)