php 将文件拆分为 $key=>$value 对,具有重复的键

我一直在努力解决这个问题,但我只是大脑冻结了。


我有一个包含多行的文件,每行由“=”分隔成单独的数据:


// Example file. Syntax: <key>=<Value>

key1=value1

key1=value2

key1=value3

key2=value1

key2=value2

key3=value1

key3=value2

key3=value3

key3=value4

我需要将这个文件分解成单独的行,并将它们全部放入一个数组中,这样 key1 包含一个 value1、2、3 的数组,key2 有它的值,key3 有它的值,依此类推。有点像这样:


Array

(

    [key1] => Array

        (

        [0] => value1

        [1] => value2

        [2] => value3

        )

    [key2] => Array

        (

        [0] => value1

        [1] => value2

        )

    [key3] => Array

        (

        [0] => value1

        [1] => value2

        [2] => value3

        [3] => value4

        )

)

到目前为止,我有以下代码:


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

$returnArray = array();

foreach ($loadFile as $line) {

  $startWith = substr(trim($line), 0, 2);

    if (empty($line) || $startWith == '//') {

          continue;

  }

  list($key, $value) = explode('=', $line);

  $returnArray[$key] = $value;

}

return $returnArray;

然而,我得到的只是:


Array ( [key1] => value3 [key2] => value2 [key3] => value4 )

我也试过


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

$returnArray = array();

foreach ($loadFile as $line) {

  $startWith = substr(trim($line), 0, 2);

    if (empty($line) || $startWith == '//') {

          continue;

  }

  $exp = explode('=', $line);

  $returnArray[$exp[0]] = $exp[1];

}

return $returnArray;

这也给了我同样的结果。我还尝试了一个 array_merge,它只是将所有内容都推入一个以数值为键的数组中。


一只斗牛犬
浏览 163回答 3
3回答

SMILET

我认为您的问题是您覆盖了密钥的值。$returnArray[$key]&nbsp;=&nbsp;$value;所以你想要的是将你的值附加到一个以$key为父级的子数组。$returnArray[$key][]&nbsp;=&nbsp;$value;随着[]你追加$value到底层数组。

函数式编程

为了好玩,只需将它们转换为ini文件的数组语法并解析它:$result = parse_ini_string(str_replace('=', '[]=', file_get_contents('file.txt')));更有趣的是,把它们变成一个查询字符串并解析它:parse_str(str_replace('=', '[]=', implode('&', file('file.txt'))), $result);两者都产生:Array(&nbsp; &nbsp; [key1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => value1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => value2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => value3&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [key2] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => value1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => value2&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [key3] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => value1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => value2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => value3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [3] => value4&nbsp; &nbsp; &nbsp; &nbsp; ))

扬帆大鱼

你应该将你的值附加到 $returnArray[$key] 的子数组中array_push($returnArray[$key],$value)&nbsp;;
打开App,查看更多内容
随时随地看视频慕课网APP