dongshuo6503 2018-06-07 10:12
浏览 409
已采纳

如何将TXT文件的内容插入JSON文件

I want import the "links" from a links.txt file and put it on a JSON file but the result is like:

{"domain":[ "www.google.es","www.yahoo.com","www.example.com"],
 "id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
 "id":6
},
{"domain":["www.google.es","www.yahoo.com","www.example.com"],
 "id":6
}

Expected:

{"domain":"www.google.es","id":6},
{"domain":"www.yahoo.com"],"id":7},
{"domain":["www.example.com"],"id":8}

As you can see, the id is the same at I want differents id and the links are added 3 times the 3 links and I want add 1 link on 1 option.

<?php
$jsonContents = file_get_contents('data/data.json');
$data = json_decode($jsonContents, true);
$fp = 'links.txt';
$last_item = end($data);
$last_item_id = $last_item['id'];
$contents_arr = file($fp,FILE_IGNORE_NEW_LINES);
foreach($contents_arr as $key=>$value) {
    $contents_arr[$key] = rtrim($value, "");
    $data[] = array(
        'domain' => $contents_arr,
        'id' => $last_item_id+1,

    );
}
$json = json_encode($data);
file_put_contents('data/data.json', $json);
  • 写回答

1条回答 默认 最新

  • doushang4293 2018-06-07 10:18
    关注

    $last_item_id+1 returns $last_item_id+1, it does not change $last_item_id variable.

    Dont change $contents_arr array used for loop inside the loop.

    You use for domain $contents_arr, which contains all values. Create for domain new array, ie:

    foreach($contents_arr as $key=>$value) {
        $data[] = array(
            'domain' => [rtrim($value, "")],
            'id' => ++$last_item_id,
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功