如何防止数组覆盖?

时间:2018-06-14 10:00:54

标签: php json

我正在尝试将文件中可用的不同json的所有键添加到数组中。我现在所做的是:

Includes

json文件是这样的:

  //Get the json file content
  $jsonData = file(__DIR__ .'/../logs/error.json');

  //Save all the json
  $json = [];

  //Iterate through the line of the file, each line is a json
  foreach($jsonData as $line)
  {
    //Convert the json in an associative array
    $array = json_decode($line, true);

    //Iterate through the json keys
    foreach($array as $k => $val)
    {
      $json[$k] = $val;
    }
  }

我会得到这个:

{"Timestamp":"2018-06-14T10:46:52.3326036+02:00","Level":"Error","MessageTemplate":"System.Exception"}
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}

因为{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"} 覆盖我猜是前一个数组,但是$json[$k]是一个新的$k所以为什么要替换数组的索引?

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

可能是你的预期输出。

//Get the json file content
  $jsonData = file(__DIR__ .'/../logs/error.json');

  //Save all the json
  $json = [];

  //Iterate through the line of the file, each line is a json
  foreach($jsonData as $line)
  {
    //Convert the json in an associative array
    $array = json_decode($line, true);

    $temp = [];
    //Iterate through the json keys
    foreach($array as $k => $val)
    {
      $temp[$k] = $val;
    }
    $json[] = $temp;
  }

答案 1 :(得分:1)

更改此行

foreach($array as $k => $val)
    {
      $json[$k] = $val;
    }

foreach($array as $k => $val)
    {
      $json[][$k] = $val;
    }

答案 2 :(得分:0)

嗯,你用相同的名字覆盖了密钥,所以在你的输出中真的没有什么意外。

您可能打算这样做:

foreach($jsonData as $line) {
    $tmp = []; //<-- set up a new array just for this iteration
    $array = json_decode($line, true);
    foreach($array as $k => $val) $tmp[$k] = $val;
    $json[] = $tmp; //<-- log the array in the master $json array
}

答案 3 :(得分:0)

//获取json文件内容

$ jsonData = file( DIR 。&#39; /../ logs / error.json&#39;);

//在关联数组中转换json

$ array = json_decode($ jsonData,true);

//保存所有json

$ json = [];

//遍历文件行,每行都是一个json

foreach($ array as $ k =&gt; $ val)   {

$json[$k] = $val;

}