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

如何将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);

图片转代码服务由CSDN问答提供 功能建议

我想从links.txt文件中导入“links”并将其放在JSON文件上,但结果是 喜欢:

  {“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 
} 
   
 
 

预期:

  {“domain”:“www.google.es”,“id”:6},
  { “域”: “www.yahoo.com”], “ID”:7},\ N { “结构域”:[ “www.example.com”], “ID”:8} 
    
 
 

正如你所看到的,我希望不同的id的id是相同的,链接是3个链接的3倍,我希望在1个选项上添加1个链接。

 &lt;?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); 
 nforeach($ contents_arr)  as $ key =&gt; $ value){
 $ contents_arr [$ key] = rtrim($ value,“
”); 
 $ data [] = array(
'domain'=&gt; $ contents_arr,  
'id'=&gt; $ last_item_id + 1,
 
); 
} 
 $ json = json_encode($ data); 
file_put_contents('data / data.json',$ json); 
    
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题